我试图从一个对象数组创建一个数组。我想从每个对象中获取父亲的名字。例如:
var people = [
{
name: "Mike Smith",
family: {
father: "Harry Smith",
}
},
{
name: "Tom Jones",
family: {
father: "Richard Jones",
}
}
];
var fathers = [];
for (var {family: { father: f } } of people) {
console.log("Father: " + f);
father.push(f);
}
无论如何在{6}中没有循环的情况下从fathers
pouplate people
数组吗?
答案 0 :(得分:5)
使用Array.prototype.map()
进行解构:
const people = [
{
name: "Mike Smith",
family: {
father: "Harry Smith",
}
},
{
name: "Tom Jones",
family: {
father: "Richard Jones",
}
}
];
const fathers = people.map(({ family: { father }}) => father);
console.log(fathers);
答案 1 :(得分:2)
在解构分配的fathers
处将值分配给target
数组。另请参阅Destructure object properties inside array for all elements
var people = [
{
name: "Mike Smith",
family: {
father: "Harry Smith",
}
},
{
name: "Tom Jones",
family: {
father: "Richard Jones",
}
}
];
var fathers = [];
[{family:{father:fathers[0]}}, {family:{father:fathers[1]}}] = people;
console.log(fathers);