Search code examples
javascriptarraysecmascript-6array-map

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 ?


Solution

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