Search code examples
javascriptarraysfunctional-programmingdata-manipulationpurely-functional

How do I transform this nested array of objects into a single array of objects?


I have this array of profile objects being returned by my api:

const profilesData = [
  {
    profile: { id: "26144385", some: "more", other: "misc" },
    photo_details: {
      photos: [{ small: "bar-1", medium: "baz-1" }]
    }
  },
  {
    profile: { id: "26144334", some: "even", other: "some more" },
    photo_details: {
      photos: [
        { small: "bar-2", medium: "baz-2" },
        { small: "fizz-2", medium: "buzz-2" }
      ]
    }
  }
];

I need to transform it so that I get a single profileWithPhotos array looks like this:

const profileWithPhotos = [
  {
    id: "26144385",
    some: "more",
    other: "misc",
    photos: [
      {
        small: "bar-1",
        medium: "baz-1"
      }
    ]
  },
  {
    id: "26144334",
    some: "even",
    other: "some more",
    photos: [
      {
        small: "bar-2",
        medium: "baz-2"
      },
      {
        small: "fizz-2",
        medium: "buzz-2"
      }
    ]
  }
];

So far I have tried breaking up the parsing into smaller functions:

const getProfiles = profilesData =>
  profilesData.map(profileData => profileData.profile);

const getSmallAndMediumPic = pic => ({ small: pic.small, medium: pic.medium });

const getPhotos = profilesData =>
  profilesData.map(profileData => profileData.photo_details.photos.map(getSmallAndMediumPic));

const profiles = getProfiles(profilesData);
const photos = getPhotos(profilesData);

const profileWithPhotos = [...profiles, { photos: photos }];

And now I get this kind of array of objects:

​​​​​[ { id: '26144385', some: 'more', other: 'misc' },​​​​​
​​​​​  { id: '26144334', some: 'even', other: 'some more' },​​​​​
​​​​​  { photos: [ [Object], [Object] ] } ]​​​​​

...which is not what I want.

Here is a working jsbin with the code above

I want to pluck and combine the first extracted collection with the second extracted collection. How do I do this?


Solution

  • You can do this with some ES6 parameter destructuring and spread syntax in object.

    const profilesData = [{"profile":{"id":"26144385","some":"more","other":"misc"},"photo_details":{"photos":[{"small":"bar-1","medium":"baz-1"}]}},{"profile":{"id":"26144334","some":"even","other":"some more"},"photo_details":{"photos":[{"small":"bar-2","medium":"baz-2"},{"small":"fizz-2","medium":"buzz-2"}]}}]
    
    const result = profilesData.map(({profile, photo_details: {photos}}) => {
      return {...profile, photos}
    })
    
    console.log(result)