Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript shortest way to map an array of objects to a new array of new objects?

I have an array of person objects, where each person have an array of profiles objects which consist of name and an image url, and a list of addresses objects which consist of lat and long properties, as follows:

var listOfPersons = [{
    addresses : [{lat:11, long:11}, {lat:22, long:22}],
    profile: [{image:"some_url1", name: "peter parker"}]
},
{
    addresses : [{lat:33, long:33}, {lat:44, long:44}],
    profile: [{image:"some_url2", name: "bruce wayne"}]
}];

I need to create a new array of objects, where each new object has an image, long, lat properties, for each set of lat long, as follows:

var expectedResult = [
{
    image:"some_url1",
  lat:11,
  long:11
},
{
    image:"some_url1",
  lat:22,
  long:22
},
{
    image:"some_url1",
  lat:33,
  long:33
},
{
    image:"some_url1",
  lat:44,
  long:44
}
];

What is the shortest way (in terms of writing code) to map\ reduce the first array into the second?

like image 234
Alex Avatar asked Nov 29 '25 19:11

Alex


1 Answers

You can use nested Array.flatMap() with Array.map() to iterate the array/address/profiles, and combine image and lat, long properties into a single object:

const listOfPersons = [{"addresses":[{"lat":11,"long":11},{"lat":22,"long":22}],"profile":[{"image":"some_url1","name":"peter parker"}]},{"addresses":[{"lat":33,"long":33},{"lat":44,"long":44}],"profile":[{"image":"some_url2","name":"bruce wayne"}]}];

const result = listOfPersons.flatMap(o =>
  o.addresses.flatMap(({ lat, long }) => 
    o.profile.map(({ image }) => ({
      image,
      lat,
      long
    }))
  )
);

console.log(result);

If you always use just the 1st profile always, you can remove one level of Array.flatMap():

const listOfPersons = [{"addresses":[{"lat":11,"long":11},{"lat":22,"long":22}],"profile":[{"image":"some_url1","name":"peter parker"}]},{"addresses":[{"lat":33,"long":33},{"lat":44,"long":44}],"profile":[{"image":"some_url2","name":"bruce wayne"}]}];

const result = listOfPersons.flatMap(o =>
  o.addresses.map(({ lat, long }) =>  ({
    image: o.profile[0].image,
    lat,
    long
  }))
);

console.log(result);
like image 137
Ori Drori Avatar answered Dec 01 '25 07:12

Ori Drori