javascript - for...of 对数组中的对象进行迭代和解构

标签 javascript ecmascript-6 destructuring

根据Mozilla docs ,这里是如何在 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"

我的问题是,如果 family 对象位于数组中,正确的解构语法应该是什么,如下所示:

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

(注意额外的一组[方括号])

试图解构使用:

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

在方括号处给出一个 Unexpected token 错误。

那么在这个例子中,我该如何使用解构来给f赋值呢?

最佳答案

您想要表示的数组结构,而不是数组索引访问。

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

当然,这假设您只需要第一个成员。如果你想要更多,你可以使用 rest 语法。

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

关于javascript - for...of 对数组中的对象进行迭代和解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46384992/

相关文章:

javascript - 嵌套对象的计算解构

variable-assignment - *为什么*列表分配会变平其左侧?

javascript - 在带有设置选择器的变量的添加函数中使用 'this'

javascript - 如何使用javascript获取第一个类名的值?

javascript - 使用单选按钮交替样式表

javascript - Array.prototype.forEach() 在使用 get 处理程序的代理上调用时不起作用

javascript - Bundle.js 文件中的 Babel 输出未正确输出

javascript - 如何停止 Promise 对象的自动解析?

Javascript 解构数组

javascript - 在 PHP 中计算哈希会在本地和测试环境中产生不同的结果。