0

I have an array of objects that looks like this below

{
  results: [
    {
      provider: 'google',
      title: 'google-title1',
      image: 'google-image1'
    },
    {
      provider: 'google',
      title: 'google-title2',
      image: 'google-image2'
    },
    {
      provider: 'facebook',
      title: 'facebook-title',
      image: 'facebook-image'
    }
  ]
}

How to convert to looks like in the below format ??? Is it possible ??

{
  results: [
    {
    google :[
    {
      title: 'google-title1',
      image: 'google-image1'
    },
    {
      title: 'google-title2',
      image: 'google-image2'
    }],
    facebook:[
    {
      title: 'facebook-title',
      image: 'facebook-image'
    }   
    
    ]
    }
  ]
}

Question: is there any javascript functionality to achieve this?

I've tried googling this, the problem is that I'm not sure what to Google for (I'm a javascript newbie). Any help is appreciated. thank you

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
BlueWild
  • 3
  • 1
  • 1
    Welcome to SO! In your result, it's a little odd that there's an array of length 1, so you'd have to access `google` with: `foo.results[0].google` instead of `foo.results.google`. It's a good idea to show your attempt at solving this, as well. – ggorlen Apr 05 '21 at 02:06

1 Answers1

0

You can easily get thousands of answers via google.com. However, in your specific case, I can give you the answer like this

const myObject = {results: [{ provider: 'google', title: 'google-title1',image: 'google-image1'},{ provider: 'google',title: 'google-title2', image: 'google-image2' }, { provider: 'facebook',title:'facebook-title', image: 'facebook-image' }]};

const result = myObject.results.reduce((acc, {provider, title, image}) => {
 acc[provider] ??= [];
 acc[provider].push({title, image});
 
 return acc;
}, {});
console.log(result);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56