let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
console.log(data)
我想将其转换成这样的一个对象
obj = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']}
我应该使用reduce吗?
答案 0 :(得分:2)
您可以使用reduce创建该对象的新版本。
reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。
使用reduce时,我们首先传递对每个项目执行的函数并返回新的输出值,然后传递第二个参数,以定义单个输出值的初始结构。
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
// o = the current output value
// i = the current item in the array
let result = data.reduce((o, i) => {
// Add the first/last names to the corresponding array
o.firstName.push(i.firstName)
o.lastName.push(i.lastName)
// Return the new current output value
return o
}, { firstName: [], lastName: [] }) // Sets the initial output value
console.log(result)
答案 1 :(得分:2)
使用Array#reduce
方法的通用解决方案。
let result = data.reduce((obj, o) => {
// get all keys of object
Object.keys(o)
// iterate over the keys
.forEach(k => {
// define property if not defined
obj[k] = obj[k] || [];
// push the value to the array
obj[k].push(o[k]);
})
// return object
return obj;
// set initial value as an object for result
}, {})
let data = [{
firstName: 'John',
lastName: 'Doe'
},
{
firstName: 'Mike',
lastName: 'Smith'
}
]
let result = data.reduce((obj, o) => {
Object.keys(o)
.forEach(k => {
obj[k] = obj[k] || [];
obj[k].push(o[k]);
})
return obj;
}, {})
console.log(result)
答案 2 :(得分:1)
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
var firstName = [];var lastName = [];
data.forEach(function(item){
firstName.push(item.firstName);
lastName.push(item.lastName);
})
let obj = {};
obj.firstName = firstName;
obj.lastName = lastName;
let dataModified = [];
dataModified.push(obj);
console.log(dataModified);
答案 3 :(得分:0)
您还可以使逻辑更通用,而与已知属性无关
let data = [{
firstName: 'John',
lastName: 'Doe'
},
{
firstName: 'Mike',
lastName: 'Smith'
}
]
let result = data.reduce((o, i) => {
for (const key in i) {
if (!o[key]) {
o[key] = [];
}
o[key].push(i[key]);
}
return o
}, {})
console.log(result)
答案 4 :(得分:0)
我们可以做的另一种简单的操作是两次调用map,一次是名字,一次是姓氏。
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
let result = {
firstName: data.map(i => i.firstName),
lastName: data.map(i => i.lastName)
}
console.log(result)
答案 5 :(得分:0)
这是一个单迭代,功能性,不变的解决方案:
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
let result = data.reduce((res, {firstName, lastName}) => ({
firstName: [firstName, ...res.firstName],
lastName: [lastName, ...res.lastName]
}), {firstName: [], lastName: []})
console.log(result)