将带有对象的数组拆分为2个数组

时间:2018-02-25 14:55:25

标签: javascript arrays object underscore.js

我有一个包含多个对象的数组。我想将这个数组拆分成多个数组。要拆分的条件是项continent

MyArray = [{continent:"europe", fruit:"orange", value:2},
           {continent:"asia", fruit:"banana", value:2},
           {continent:"europe", fruit:"apple", value:2},
           {continent:"asia", fruit:"apple", value:5}
          ];

输出:

[
 [{continent:"europe", fruit:"orange", value:2},
  {continent:"europe", fruit:"apple" value:2}
 ], [
  {continent:"asia", fruit:"banana", value:2},
  {continent:"asia", fruit:"apple" value:5}]
];

3 个答案:

答案 0 :(得分:2)

您可以搜索具有相同大陆的阵列并更新此阵列或使用实际对象推送新阵列。



var array = [{ continent: "europe", fruit: "orange", value: 2 }, { continent: "asia", fruit: "banana", value: 2 }, { continent: "europe", fruit: "apple", value: 2 }, { continent: "asia", fruit: "apple", value: 5 }],
    grouped = array.reduce(function (r, o) {
        var group = r.find(([{ continent }]) => continent === o.continent)
        if (group) {
            group.push(o);
        } else {
            r.push([o]);
        }
        return r;
    }, []);
    
console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

获取大陆并使用filter获取匹配的元素



var MyArray = [{
  continent: "europe",
  fruit: "orange",
  value: 2
}, {
  continent: "asia",
  fruit: "banana",
  value: 2
}, {
  continent: "europe",
  fruit: "apple",
  value: 2
}, {
  continent: "asia",
  fruit: "apple",
  value: 5
}];
var getAllContinents = [];
 // getting the unique continent name
MyArray.forEach(function(item) {
  // if the continent  name is not present then push it in the array
  if (getAllContinents.indexOf(item.continent) === -1) {
    getAllContinents.push(item.continent)
  }
})
var modifiedArray = [];
//iterate over the continent array and find the matched elements where 
// continent name is same
getAllContinents.forEach(function(item) {
  modifiedArray.push(MyArray.filter(function(cont) {
    return cont.continent === item
  }))
})
console.log(modifiedArray)




答案 2 :(得分:0)

您还可以使用具有指定属性值的键创建对象。这样您就可以轻松访问所需的数组。

您可以使用:

示例:

let data = [{continent:"europe", fruit:"orange", value:2},      
            {continent:"asia", fruit:"banana", value:2},
            {continent:"europe", fruit:"apple", value:2},
            {continent:"asia", fruit:"apple", value:5}];

let result = data.reduce((acc, obj) => {
  acc[obj.continent] = acc[obj.continent] || [];
  acc[obj.continent].push(obj);
  return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }