Home > Software engineering >  How to merge 2 objects into one - javascript
How to merge 2 objects into one - javascript

Time:04-23

I need help with solution on this. I have two objects: Input:

obj1 =  [{name:A}, {name:B}, {name:C}...,]
obj2 = [{value:1}, {name:2}, {name:3}...,]

And i need to make from these 2 objects one. Output:

obj3 = [{A:1}, {B:2}, {C:3}...,]

Anybody know how to merge obj and obj2 to one? Thanks!

CodePudding user response:

If you have consitent nameing, you could map with index.

const
    names = [{ name: 'A' }, { name: 'B' }, { name: 'C' }],
    values = [{ value: 1 }, { value: 2 }, { value: 3 }],
    result = names.map(({ name }, i) => ({ [name]: values[i].value }));

console.log(result);

CodePudding user response:

You could do this

const obj1 = [{name:'A'}, {name:'B'}, {name:'C'}];
const obj2 = [{value:1}, {value:2}, {value:3}];

const merged = Array.from({length:Math.min(obj1.length, obj2.length)}).map((_,i) => {
  return { [obj1[i].name]: obj2[i].value };
});

console.log(merged);

  • Related