Thi*_*aja 0 javascript arrays array-map ecmascript-6
假设我有一个像下面这样的对象阵列调用电影.
movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}]
Run Code Online (Sandbox Code Playgroud)
无论如何我可以从每个对象中提取特定键的值吗?喜欢这个标题数组.
titles = ['Black Panther','Avengers','Justice League','Infinity War','Spider Man']
Run Code Online (Sandbox Code Playgroud)
目前我正在使用map功能.有没有其他方法可以实现这一点,而无需迭代每个对象.这可以通过ES6休息/传播功能实现吗?
不,如果不循环遍历数组,就无法做到这一点.不,休息/传播无济于事.
你说你正在使用map,这可能是最简单的方法:
titles = movies.map(e => e.title);
Run Code Online (Sandbox Code Playgroud)
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}];
const titles = movies.map(e => e.title);
console.log(JSON.stringify(titles));Run Code Online (Sandbox Code Playgroud)
或与解构:
titles = movies.map(({title}) => title);
Run Code Online (Sandbox Code Playgroud)
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}];
const titles = movies.map(({title}) => title);
console.log(JSON.stringify(titles));Run Code Online (Sandbox Code Playgroud)
你也可以使用for-of:
titles = [];
for (const {title} of movies) {
titles.push(title);
}
Run Code Online (Sandbox Code Playgroud)
const movies = [{ id : 1,title : 'Black Panther'},{ id : 2,title : 'Avengers'},{ id : 1,title : 'Justice League'},{ id : 4,title : 'Infinity War'},{ id : 5,title : 'Spider man'}];
const titles = [];
for (const {title} of movies) {
titles.push(title);
}
console.log(JSON.stringify(titles));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |