如何将换行符插入到创建的 Javascript 对象数组中

ton*_*zza 0 javascript arrays newline

我创建一个空数组,创建对象,将现有的键:值数据放入对象中,将对象推入数组,按一个键:值对对数组的对象进行排序,对数组进行字符串化,并在控制台中记录它。

这一切正常。但是,如果我尝试使用 \n 插入换行符,则当我 console.log 字符串化数组时,不再返回每个对象内的数据。相反,我只是在控制台上得到 [object, Object]。

我试过把 \n 放在任何地方。在创建的对象内部为“\n”,也为\n。创建的对象后为“\n”或\n。在字符串化之前,在字符串化之后。似乎没有任何效果。

//create new empty array called indices
var indices = [];
//create new object called newobject and fill it with key:value pair data
var newobject = { name: y[i].Name, age: y[i].age };
//push newobject into indices array
indices.push(newobject);
//create new object called newobject2 and fill it with key:value pair data
varnewobject2 = { country: y[i].Name, age: y[i].age, height: y[i].height };
//push newobject2 into indices array
indices.push(newobject2);
//sort objects in indices array by age values lowest to highest
indices.sort((a, b) => a.age - b.age);
//new variable called output is the sorted indices array stringified
var output = JSON.stringify(indices);
//console.log variable output
console.log(output);
Run Code Online (Sandbox Code Playgroud)

当我将所有这些新对象所在的字符串化数组进行 console.log 记录时,我希望数组中的每个创建的对象都打印到一个新行。上面的代码有效。我只是不知道在每个新对象后在哪里或如何插入换行符。每当我尝试插入 \n 时,给定的输出显示为:

[output Output]
Run Code Online (Sandbox Code Playgroud)

感谢您的善意考虑。

T.J*_*der 6

你可以让JSON.stringify你为你做格式化:

var output = JSON.stringify(indices, null, 0);
Run Code Online (Sandbox Code Playgroud)

...但它不会在开头[和第一个对象之间放置换行符:

var output = JSON.stringify(indices, null, 0);
Run Code Online (Sandbox Code Playgroud)

您可以使用大于 4 的值并获得格式良好的输出,但并不完全符合您的要求:

var indices = [];
var newobject = { name: "name1", age: 21 };
indices.push(newobject);
var newobject2 = { country: "country1", age: 42, height: 6 };
indices.push(newobject2);
indices.sort((a, b) => a.age- b.age);
var output = JSON.stringify(indices, null, 0);
console.log(output);
Run Code Online (Sandbox Code Playgroud)

或者,由于您知道最外层位是一个数组,您可以循环遍历并自己创建字符串:

var output = "[\n" +
  indices.map(entry => JSON.stringify(entry)).join(",\n") +
  "\n]";
Run Code Online (Sandbox Code Playgroud)

var indices = [];
var newobject = { name: "name1", age: 21 };
indices.push(newobject);
var newobject2 = { country: "country1", age: 42, height: 6 };
indices.push(newobject2);
indices.sort((a, b) => a.age- b.age);
var output = JSON.stringify(indices, null, 4);
console.log(output);
Run Code Online (Sandbox Code Playgroud)