0

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 ?

Thidasa Pankaja
  • 930
  • 8
  • 25
  • 44

2 Answers2

5

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));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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)
Markus
  • 1,598
  • 2
  • 13
  • 32