将 JavaScript 对象数组展平为对象


为了将 JavaScript 对象数组展平为一个对象,我们创建了一个函数,其中仅将对象数组用作参数。它返回一个展平的对象,其键追加了索引。时间复杂度为 O(mn),其中 n 为数组的大小,m 为每个对象中的属性数。但是,其空间复杂度为 O(n),其中 n 为实际数组的大小。

示例

//code to flatten array of objects into an object
//example array of objects
const notes = [{
   title: 'Hello world',
   id: 1
}, {
   title: 'Grab a coffee',
   id: 2
}, {
   title: 'Start coding',
   id: 3
}, {
   title: 'Have lunch',
   id: 4
}, {
   title: 'Have dinner',
   id: 5
}, {
   title: 'Go to bed',
   id: 6
}, ];
const returnFlattenObject = (arr) => {
   const flatObject = {};
   for(let i=0; i<arr.length; i++){
      for(const property in arr[i]){
         flatObject[`${property}_${i}`] = arr[i][property];
      }
   };
   return flatObject;
}
console.log(returnFlattenObject(notes));

输出

控制台中的输出如下 -

[object Object] {
   id_0: 1,
   id_1: 2,
   id_2: 3,
   id_3: 4,
   id_4: 5,
   id_5: 6,
   title_0: "Hello world",
   title_1: "Grab a coffee",
   title_2: "Start coding",
   title_3: "Have lunch",
   title_4: "Have dinner",
   title_5: "Go to bed"
}

更新时间:2020 年 8 月 18 日

2K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.