假设我们有一个像这样的数组的数组-
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' ] } ]