從 JavaScript 物件陣列中單獨提取陣列


假設我們有一個物件陣列,如下所示 −

const arr = [{
   name : 'Client 1',
   total: 900,
   value: 12000
}, {
   name : 'Client 2',
   total: 10,
   value: 800
}, {
   name : 'Client 3',
   total: 5,
   value : 0
}];

我們需要編寫一個 JavaScript 函式,該函式採用一個這樣的陣列,併為每個物件屬性提取一個單獨的陣列。

因此,每個物件的 name 屬性有一個數組,total 有一個數組,value 有一個數組。如果存在更多屬性,我們將分離更多陣列。

示例

其程式碼如下 −

const arr = [{
   name : 'Client 1',
   total: 900,
   value: 12000
}, {
   name : 'Client 2',
   total: 10,
   value: 800
}, {
   name : 'Client 3',
   total: 5,
   value : 0
}];
const separateOut = arr => {
   if(!arr.length){
      return [];
   };
   const res = {};
   const keys = Object.keys(arr[0]);
   keys.forEach(key => {
      arr.forEach(el => {
         if(res.hasOwnProperty(key)){
            res[key].push(el[key])
         }else{
            res[key] = [el[key]];
         };
      });
   });
   return res;
};
console.log(separateOut(arr));

輸出

然後控制檯中的輸出將為 −

{
   name: [ 'Client 1', 'Client 2', 'Client 3' ],
   total: [ 900, 10, 5 ],
   value: [ 12000, 800, 0 ]
}

更新時間:20-11-2020

1 千次+ 瀏覽

開啟你的 職業生涯

完成學習獲得認證

開始
廣告
© . All rights reserved.