Javascript-解构对象数组

问题描述

试图更好地了解结构调整。
如果我有这样的对象:

const starWars = {
  count: 2,data: [
   {name: 'Luke Skywalker',films: ['Empire Strikes Back','The Force Awakens']},{name: 'Han Solo',films: ['New Hope','Return of the Jedi']}
  ]};  

我可以这样分解数据部分:

const {data: allCharMovies} = starWars;
console.log(allCharMovies[1].name);  

或者我可以尝试做:

const { count,data: [{name: nameCh,films: movies}]} = starWars;
console.log(nameCh,movies[1]);   

但是,那只能使我的电影获得“卢克·天行者”(Luke Skywalker)的支持-如果我以第二种方式进行操作,如何访问“汉·索罗”部分?

解决方法

您可以在销毁data的同时在数组中添加另一个销毁对象:

const starWars = {
  count: 2,data: [
    { name: 'Luke Skywalker',films: ['Empire Strikes Back','The Force Awakens'] },{ name: 'Han Solo',films: ['New Hope','Return of the Jedi'] }
  ]
};


const {
  count,data: [
    { name: nameCh,films: movies },{ name: name2,films: movies2 }
  ]
} = starWars;

console.log(nameCh,movies[1]);
console.log(name2,movies2[1]);

此外,您可以使用rest syntax来获取除第一部电影以外的所有电影:

const starWars = {
  count: 2,'Return of the Jedi'] },{ name: 'Chewbacca','The Force Awakens','The Last Jedi'] }
  ]
};


const { count,data: [{ name: nameCh,...otherMovies] } = starWars;

console.log(nameCh,movies[1]);
console.log(otherMovies[0].name,otherMovies[0].films[1]);
console.log(otherMovies[1].name,otherMovies[1].films[2]);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...