问题描述
试图更好地了解结构调整。
如果我有这样的对象:
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]);