简体   繁体   中英

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 ?

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

You can use array destructuring (any remaining array elements are simply ignored):

                        // vv            vv
for (var {name: n, family: [ {father: f} ] } of people)
  // ...

Alternatively, since arrays are just objects, you can use object destructuring with the index as key:

                        // vvvvv            vv
for (var {name: n, family: { 0: {father: f} } } of people)
  // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM