繁体   English   中英

如何在不迭代数组的情况下提取对象数组中特定键的值?

[英]How to extract Values of particular key in an object array without iterating over the array?

假设我有一个像下面这样的对象数组调用影片

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 = ['Black Panther','Avengers','Justice League','Infinity War','Spider Man']

目前,我正在使用map功能。 还有其他方法可以实现此目标而无需遍历每个对象。 可以使用ES6的剩余/扩展功能来实现吗?

不,如果不循环遍历数组,则无法执行此操作。 不,休息/散布也无济于事。

您已经说过您正在使用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)); 

不,传播无法做到这一点。 您可以将map与参数解构结合起来:

list.map(({ title }) => title)

或者,您可以使用lodash/map ,它是您的用例的简写形式:

import { map } from 'lodash'
map(list, 'title')

使用lodash/fp ,您甚至可以在其他地方重用您的功能:D

import { map } from 'lodash/fp'
const getTitles = map('title')
getTitles(list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM