我当前输入以下内容:
[
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
];
输出应如下:
[
{ firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' },
{ firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager' }
];
我编写了以下代码:
function transformEmployeeData(array) {
let newArr = [];
for(var i = 0; i< array.length; i++) {
let newObj = {}
for(var j = 0; j< array[i].length; j++) {
newObj[array[i][j][0]] = array[i][j][1]
}
newArr.push(newObj);
}
return newArr;
}
但是,我想尝试使用.map()
和.reduce()
函数。我该如何实施?
答案 0 :(得分:2)
最简单的方法是可能使用.map()
,然后使用Object.fromEntries()
作为映射函数,如下所示:
const arr = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
];
const res = arr.map(Object.fromEntries);
console.log(res);
但是,如果您确实要使用.reduce()
,则可以使用.map()
和.reduce()
为您构建对象:
const arr = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
];
const res = arr.map(
entries => entries.reduce((acc, [key, value]) => ({...acc, [key]: value}), {})
);
console.log(res);
上面的方法使用.reduce()
遍历内部数组中的[key, value]
对数组。对于每个键值对,您可以destructure(([key, value]) =>
)将其从数组中拉出key
和value
。然后,您可以返回一个对象,用作acc
累加器的下一个值。您返回的对象是acc
(最初是{}
)和当前键值对的组合对象。这是通过将spread syntax(...
)与computed property names({[key]: value}
)一起完成的。
最后一种方法是将每个内部[key, value]
映射到一个对象:
[
[ { "firstName": "Joe" }, { "lastName": "Blow" }, { "age": 42 }, { "role": "clerk" } ],
[ { "firstName": "Mary" }, { "lastName": "Jenkins" }, { "age": 36 }, { "role": "manager" } ]
]
然后,您可以使用Object.assign()
将此数组映射到对象数组,其中Object.assign()
的每个参数都是内部数组中的对象。这将“合并”数组中的每个对象以形成一个更大的对象:
const arr = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
];
const res = arr.map(
entries => entries.map(([k, v]) => ({[k]: v}))
).map(arr => Object.assign(...arr));
console.log(res);