使用javascript在单个数组中合并多个对象结果集的数组

时间:2016-01-19 14:30:57

标签: javascript arrays angularjs object merge

我有一个包含多个对象的数组结果,我需要使用java-script将此结果集合并到单个数组中。我尝试过很多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...
  }

]

2 个答案:

答案 0 :(得分:2)

您可以使用reduceconcat快速转换:

arr.reduce(function(a, b){  return a.concat(b); });

示例:

&#13;
&#13;
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');
&#13;
<h1>Before</h1>
<pre id="before"></pre>
<h1>After</h1>
<pre id="results"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试:

var result = [];
for (var i=0; i<Response.length; ++i) {
  for (var j=0; j<Response[i].length; ++j) {
    result.push(Response[i][j]);
  }
}
相关问题