What would be the "correct" way of transforming an array of objects into an object that contains an array?
Suppose I have this array that contains objects:
const paintings = [ { painting: "Mona Lisa" }, { painting: "The Starry Night" }, { painting: "The Last Supper" }, { painting: "Girl with a Pearl Earring" }, { painting: "American Gothic" }, { painting: "The Night Watch" } ];
And I would like to transform it into this:
const paintings = { artworks: [ "Mona Lisa", "The Starry Night", "The Last Supper", "Girl with a Pearl Earring", "American Gothic", "The Night Watch" ] };
I know that I can accomplish this with two nested loops like below, but is there a more "elegant" way of doing it? I think that these tasks are nowadays usually solved using map or reduce functions but I find them a bit confusing to use. I would like to learn though!
const paintingsNew = { artworks: [] }; for (const painting of paintings) { for (const val of Object.values(painting).values()) { paintingsNew.artworks.push(val); } } console.log(paintingsNew); // { artworks: // [ 'Mona Lisa', // 'The Starry Night', // 'The Last Supper', // 'Girl with a Pearl Earring', // 'American Gothic', // 'The Night Watch' ] }
artworks
maps every{painting:"MonaLisa", artist: ...}
to itspainting
. In Computer Science a projection.\$\endgroup\$