객체의 JavaScript 배열을 객체로 평면화하기 위해 객체의 배열을 인수로 사용하는 함수를 만들었습니다. 인덱스에 의해 키가 추가된 평평한 객체를 반환합니다. 시간 복잡도는 O(mn)입니다. 여기서 n은 배열의 크기이고 m은 각 객체의 속성 수입니다. 그러나 spacecomplexity는 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"
}