Reputation: 674
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?
Upvotes: 3
Views: 253
Reputation: 2776
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)
Upvotes: 1
Reputation: 5863
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)
Upvotes: 1
Reputation: 81
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
Upvotes: 4
Reputation: 23664
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)
Upvotes: 1