將 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" }
廣告