如何將 JavaScript 中巢狀陣列對轉換為陣列中的物件?
假設我們有一個這樣的陣列 −
const arr = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ] ];
我們要求寫一個接受此類陣列的 JavaScript 函式。此函式應基於此陣列陣列構建一個物件陣列。
輸出陣列應為每個唯一使用者及其他相關詳細資訊包含一個物件。
因此,該陣列的輸出應如下所示 −
const output = [ {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'}, {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'} ];
示例
程式碼如下 −
const arr = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ] ]; const convertToObject = (arr = []) => { const empty = {}; const res = arr.map(el => { const object = this; el.forEach(attr => { let name = attr[0], value = attr[1]; object[name] = value; return object; }, object); return this; }, empty); return res; } console.log(convertToObject(arr));
輸出
控制檯中輸出為 −
[ { firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk', 'firstName,Mary': [ 'lastName', 'Jenkins' ] } ]
廣告