Noitidart
Noitidart

Reputation: 37238

ES6 iterative destructure

I was trying to create a array from an array of objects. I wanted to get the name of father from each object. For example:

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);
}

Is there anyway to do pouplate the fathers array from people without the loop in es6?

Upvotes: 0

Views: 248

Answers (2)

guest271314
guest271314

Reputation: 1

Assign the values to fathers array at target of destructuring assignment. See also 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);

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191946

Use Array.prototype.map() with destructuring:

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

Upvotes: 5

Related Questions