简体   繁体   中英

Merge two objects together

I have two objects:

a = {id: "1", value: "hello"}
b = {id: "2", value: "bye"}

That I want to convert to:

c = { 1: "hello", 2: "bye" }

Thus creating a single new object without any nested subjects.

I have tried a few ways but not quite getting what I need. Such as:

Object.keys(a).forEach((key) => { a[key] = b[key]; });

You could use .reduce :

 a = {id: "1", value: "hello"} b = {id: "2", value: "bye"} c = [a, b].reduce((carry, current) => { carry[current.id] = current.value; return carry }, {}) console.log(c) 

Just create a new blank object and copy the values..

 var a = {id: "1", value: "hello"} var b = {id: "2", value: "bye"} var c = {}; c[a.id] = a.value; c[b.id] = b.value; console.log(c); 

If using new ESNext features this is even easier.

 const a = {id: "1", value: "hello"} const b = {id: "2", value: "bye"} const c = { [a.id]: a.value, [b.id]: b.value }; console.log(c); 

You could do this with Object.assign and map() methods.

 const a = {id: "1", value: "hello"} const b = {id: "2", value: "bye"} const result = Object.assign({}, ...[a, b].map(({id, value}) => ({[id]: value}))); console.log(result) 

Simple way, with a loop so it does all your elements:

var list = [
    {id: "1", value: "hello"},
    {id: "2", value: "bye"}
    // ... more elements
];

var c = {};
list.forEach(function (element) {
    c[element['id']] = element['value'];
    // or c[element.id] = element.value;
});

Another alternative

 var a = {id: "1", value: "hello"} var b = {id: "2", value: "bye"} var c = {}; [a, b].forEach(function(x){ c[x.id] = x.value; }); console.log(c); 

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