簡體   English   中英

將帶有對象的數組拆分為2個數組

[英]split an array with object to 2 arrays

我有一個包含多個對象的數組。 我想把這個數組拆分成多個數組。 分裂的標准是項目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}]
];

您可以搜索具有相同大陸的陣列並更新此陣列或使用實際對象推送新陣列。

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

獲取大陸並使用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) 

您還可以使用具有指定屬性值的鍵創建對象。 這將允許您非常輕松地訪問所需的陣列。

你可以使用:

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM