javascriptobjectkey

Javascript, map a object array to return new array


I have been looking online for a solution. Most show you how to map an array but not an object array:

club    = [];

club[0] = {};
club[0].team        = "Manchester United";
club[0].ground  = "Old Trafford";


club[1] = {};
club[1].team        = "Manchester City";
club[1].ground  = "Etihad";

club[2] = {};
club[2].team        = "Liverpool";
club[2].ground  = "Anfield";

I want to product a new array with just the ground object key from the original object. This eventually will include a lot more teams that can be added and deleted thus why I want to map a new array of the ground names.

I should end up with a new array:

search = ['Old Trafford', 'Etihad', 'Liverpool'];

I need to map rather that a for/next or for/each.

Thanks.


Solution

  • const club = [
    { team: "Manchester United", ground: "Old Trafford" },
    { team: "Manchester City", ground: "Etihad" },
    { team: "Liverpool", ground: "Anfield" }
    ];
    
    const search = club.map(club => club.ground);
    
    console.log(search);
    // Output: ['Old Trafford', 'Etihad', 'Anfield']