ES6迭代解构

Noi*_*art 0 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);
}
Run Code Online (Sandbox Code Playgroud)

反正有没有在es6中没有循环的情况下制作fathers阵列people

Ori*_*ori 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);
Run Code Online (Sandbox Code Playgroud)

  • `people.map(person => person.family.father)`对我来说似乎更具可读性. (7认同)