假设我有一个对象数组调用电影,如下所示。
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'}]
我是否可以从每个对象中提取特定键的值?就像这个 titles 数组一样。
titles = ['Black Panther','Avengers','Justice League','Infinity War','Spider Man']
目前我正在使用 map
函数来完成此操作。有没有其他方法可以在不迭代每个对象的情况下实现此目的。这可以使用 ES6 休息/传播功能 来实现吗?
最佳答案
不,如果不循环数组就无法执行此操作。不,休息/拉伸(stretch)不会有帮助。
您说过您正在使用map
,这可能是最简单的方法:
titles = movies.map(e => e.title);
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));
或者通过解构:
titles = movies.map(({title}) => title);
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));
您还可以使用for-of
:
titles = [];
for (const {title} of movies) {
titles.push(title);
}
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));
关于javascript - 如何在不迭代数组的情况下提取对象数组中特定键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49208311/