2 回答
TA贡献1818条经验 获得超7个赞
假设您希望名称作为键,yxou可以构建条目并从中构建对象。
var tab = [{ firstName: 'John', lastName: 'Doe', situation: 'maried', familyMembers: 5 }, { firstName: 'Jack', lastName: 'Daniel', situation: 'single', familyMembers: 6 }],
result = Object.fromEntries(tab.map(({ firstName, lastName, familyMembers }) =>
[firstName, { [lastName]: familyMembers }]
));
console.log(result);
TA贡献2037条经验 获得超6个赞
map()始终返回函数结果的数组。
您可以改用reduce()
var tab = [{
firstName: 'John',
lastName: 'Doe',
situation: 'maried',
familyMembers: 5,
},
{
firstName: 'Jack',
lastName: 'Daniel',
situation: 'single',
familyMembers: 6,
}
];
var result = tab.reduce((obj, item) => {
obj[item.firstName] = {
[item.lastName]: item.familyMembers
};
return obj;
}, {});
console.log(result);
添加回答
举报