3

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?

HenrijsS
  • 656
  • 4
  • 25

4 Answers4

4

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

  • @Kinglish posted this with a forEach. What difference does this make with using map? – HenrijsS May 28 '21 at 20:17
  • 1
    Both are simillar, but different. Map is more the functional way, and create a new array. forEach allows you to change the original array. The map function will receive a function that will run on each item on array and create a new array with all created objects. You can read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map For performance point, map is slight faster (as seen here: https://morioh.com/p/b2d058745cb8) – Daniel Ramos May 28 '21 at 20:18
1

A simple forEach loop using index would do the trick

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

let newarray = [];
services.iconAndLink.forEach((el, index) => newarray.push({
      icon: el,
      name: services.name[index]
    })
    );

    console.log(newarray)
Kinglish
  • 23,358
  • 3
  • 22
  • 43
1

const services={iconAndLink:["Icon1","Icon2","Icon3"],name:["Name1","Name2","Name3"]};
    
const res = services.name.map((e, i) => ({
  icon: e,
  name: services.iconAndLink[i]
}))

console.log(res)
ulou
  • 5,542
  • 5
  • 37
  • 47
1

Assuming the arrays are of the same size, you can do:

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

for (let i = 0; i < services.iconAndLink.length; i++) {
    newArr.push({icon: services.iconAndLink[i], name: services.name[i]})
}

console.log(newArr)
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12