简体   繁体   中英

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. Is there any other way to achieve this without iterating over every object. Can this be achieved using ES6 rest/spread feature ?

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:

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 :

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:

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

Or you could use lodash/map , which has a shorthand for your usecase:

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

And with lodash/fp , you can even reuse your function elsewhere :D

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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