按字段分组对象数组

时间:2019-10-23 10:12:50

标签: javascript sorting

var array1= [
    { name : "1", desc: "in odd", cat:"1" },
    { name : "3", desc: "in odd" ,cat:"2" }
];

var array2= [
    { name : "1", desc: "in even", cat:"1"},
    { name : "2", desc: "in even", cat:"1" },
    { name : "4", desc: "in even", cat:"1" }
];

我想合并数组并合并为一个数组,以便它可以将任何cat分组(最终输出应该是对象数组)

合并后,我想按名称对合并列表进行排序。我们可以通过一些方法来优化实现相同目的的方法吗?

2 个答案:

答案 0 :(得分:1)

您正在寻找类似的东西吗?

var array1 = [
  { name: "1", desc: "in odd", cat: "1" },
  { name: "3", desc: "in odd", cat: "2" }
];

var array2 = [
  { name: "1", desc: "in even", cat: "1" },
  { name: "2", desc: "in even", cat: "1" },
  { name: "4", desc: "in even", cat: "1" },
];
var array3 = array1.concat(array2);

var objConsolidated = {};

array3.forEach(element => {
  if(objConsolidated[element.cat]){
    objConsolidated[element.cat].push(element);
  } else {
    objConsolidated[element.cat] = [];
    objConsolidated[element.cat].push(element);
  }
});

console.log(objConsolidated);

答案 1 :(得分:0)

你是说

var array1= [
    { name : "1", desc: "in odd", cat:"1" },
    { name : "3", desc: "in odd" ,cat:"2" }
];

var array2= [
    { name : "1", desc: "in even", cat:"1"},
    { name : "2", desc: "in even", cat:"1" },
    { name : "4", desc: "in even", cat:"1" }
];



function getCatItems(cat){
    var n = [array1, array2].flat();
    return n.filter(i=>(i.cat==cat));
}
 console.log(getCatItems("1"));