简体   繁体   English

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

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

Let's say I have an object array call movies like below. 假设我有一个像下面这样的对象数组调用影片

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'}]

Is there anyway I can extract the value of particular key from every object ? 无论如何,我可以从每个对象中提取特定键的值吗? Like this titles array. 像这样的标题数组。

titles = ['Black Panther','Avengers','Justice League','Infinity War','Spider Man']

At the moment I'm doing it using map function. 目前,我正在使用map功能。 Is there any other way to achieve this without iterating over every object. 还有其他方法可以实现此目标而无需遍历每个对象。 Can this be achieved using ES6 rest/spread feature ? 可以使用ES6的剩余/扩展功能来实现吗?

No, you cannot do this without looping through the array. 不,如果不循环遍历数组,则无法执行此操作。 And no, rest/spread wouldn't help. 不,休息/散布也无济于事。

You've said you're using map , which is probably the simplest way: 您已经说过您正在使用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)); 

or with destructuring: 或具有破坏​​性:

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)); 

You could also use for-of : 您也可以使用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)); 

No, spread can't do that. 不,传播无法做到这一点。 You could combine map with argument deconstruction: 您可以将map与参数解构结合起来:

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

Or you could use lodash/map , which has a shorthand for your usecase: 或者,您可以使用lodash/map ,它是您的用例的简写形式:

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

And with lodash/fp , you can even reuse your function elsewhere :D 使用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