为了将对象的JavaScript数组平整为一个对象,我们创建了一个函数,该函数将对象数组作为唯一参数。它返回一个扁平化的对象,并在其索引后附加键。时间复杂度为O(mn),其中n是数组的大小,m是每个对象中的属性数。但是,其空间复杂度为O(n),其中n是实际数组的大小。
//code to flatten array of objects into an object
//对象数组示例
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"
}