将一个带有对象的数组拆分成两个数组

3

我有一个包含多个对象的数组。我想将这个数组拆分成多个数组。拆分的标准是项目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个回答

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; }


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)


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; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接