ES6迭代解构

时间:2016-11-01 19:13:03

标签: javascript ecmascript-6

我试图从一个对象数组创建一个数组。我想从每个对象中获取父亲的名字。例如:

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数组吗?

2 个答案:

答案 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);

相关问题