Search code examples
javascriptecmascript-6destructuring

for...of iteration and destructuring with an object inside an array


According to the Mozilla docs, here is how to use destructuring inside a for of loop:

var people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (var {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

My question is, what would the correct destructuring syntax be in case the family object was located inside an array, like this:

var people = [
  {
    name: 'Tom Jones',
    family: [
     {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
     }
    ],
    age: 25
  }
];

(Note the extra set of [square brackets])

Attempting to destructure using:

for (var {name: n, family[0]: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

gives an Unexpected token error at the square bracket.

So in this example, how do I use destructuring to assign a value to f?


Solution

  • You want the array structure represented, not the array index access.

    var people = [{
      name: 'Tom Jones',
      family: [{
        mother: 'Norah Jones',
        father: 'Richard Jones',
        brother: 'Howard Jones'
      }],
      age: 25
    }];
    
    // Describe the structure -v-----------v
    for (var {name: n, family: [{father: f}]} of people) {
      console.log('Name: ' + n + ', Father: ' + f);
    }

    Of course, this assumes you want only the first member. If you want more, you can use the rest syntax.

    var people = [{
      name: 'Tom Jones',
      family: [{
        mother: 'Norah Jones',
        father: 'Richard Jones',
        brother: 'Howard Jones'
      }],
      age: 25
    }];
    
    for (var {name: n, family: [{father: f}, ...rem]} of people) {
      console.log('Name: ' + n + ', Father: ' + f);
      console.log("Remaining values: %s", rem.length);
    }