Search code examples
javascriptarraysjavascript-objects

Merge two arrays to multiple objects


I already have an object witch has two arrays:

const services = {
        iconAndLink: [
            'Icon1',
            'Icon2',
            'Icon3',
        ],
        name: [
            'Name1',
            'Name2',
            'Name3',
        ],
    };

I looked into Object.assign(), array.reduce(), map etc... and can't seem to find a decent answer here that merges these two.

For final result I need:

services = [
        {
            icon: 'Icon1',
            name: 'Name1'
        },
        {
            icon: 'Icon2',
            name: 'Name2'
        },
        {
            icon: 'Icon3',
            name: 'Name3'
        },
    ]

Note that I need to have the icon and name keys.

Is this even possible in js?


Solution

  • This should work

    const services = {
      iconAndLink: ["Icon1", "Icon2", "Icon3"],
      name: ["Name1", "Name2", "Name3"],
    };
    
    let result = services.iconAndLink.map(function (icon, index) {
      return { icon: services.iconAndLink[index], name: services.name[index] };
    });
    
    
    console.log(result);

    Make sure both arrays same the same length and both are ordered