简体   繁体   English

for ...使用数组内的对象进行迭代和解构

[英]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: 根据Mozilla文档 ,这里是如何在for of循环中使用解构:

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: 我的问题是,如果family对象位于数组中,正确的解构语法是什么,如下所示:

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. 在方括号处出现Unexpected token错误。

So in this example, how do I use destructuring to assign a value to f ? 所以在这个例子中,我如何使用解构来为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)
  // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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