简体   繁体   中英

How to merge 2 objects into one - javascript

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

obj1 =  [{name:A}, {name:B}, {name:C}...,]
obj2 =  [{value:1}, {value:2}, {value: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!

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);

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)}, (_,i) => { return { [obj1[i].name]: obj2[i].value }; }); console.log(merged);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM