我有一个包含多个对象的数组结果,我需要使用 java 脚本将此结果集合并到单个数组中。我尝试过许多 JavaScript 函数,但没有成功。另外,这个在使用 array.push 后生成了响应。
响应
[
[Object {
category_of_student = "Freshman", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
Object {
category_of_student = "Freshman", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
Object {
category_of_student = "Ophomore", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
26 more...
],
[Object {
category_of_student = "Junior", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
}]
]
代码
var yourCat = item.category_of_student;
var optionVal = [];
for (i = 0; i < yourCat.length; i++) {
var res = ($filter('filter')(item, {
category_of_student: yourCat[i]
}));
optionVal.push(res);
}
需要结果
[
Object {
category_of_student = "Freshman", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
Object {
category_of_student = "Freshman", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
Object {
category_of_student = "Ophomore", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
},
26 more...,
Object {
category_of_student = "Junior", your_school = "(BA Bs)Bachelor of Scien...Business Administration", college = "Business of Unit", more...
}
]
最佳答案
您可以使用 reduce
和 concat
快速转换它:
arr.reduce(function(a, b){ return a.concat(b); });
示例:
var arr = [
[{
category_of_student : "Freshman",
your_school : "(BA Bs)Bachelor of Scien...Business Administration",
college : "Business of Unit"
},
{
category_of_student : "Freshman",
your_school : "(BA Bs)Bachelor of Scien...Business Administration",
college : "Business of Unit"
},
{
category_of_student : "Freshman",
your_school : "(BA Bs)Bachelor of Scien...Business Administration",
college : "Business of Unit"
}],
[{
category_of_student : "Junior",
your_school : "(BA Bs)Bachelor of Scien...Business Administration",
college : "Business of Unit"
}]
]
var transformed = arr.reduce(function(a, b){ return a.concat(b); });
before.innerHTML = JSON.stringify(arr, null, '\t');
results.innerHTML = JSON.stringify(transformed, null, '\t');
<h1>Before</h1>
<pre id="before"></pre>
<h1>After</h1>
<pre id="results"></pre>
关于javascript - 使用 javascript 将多个对象结果集的数组合并到单个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879433/