arled
arled

Reputation: 2690

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

Upvotes: 2

Views: 484

Answers (5)

elarmando
elarmando

Reputation: 579

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

Upvotes: 1

DonJoe
DonJoe

Reputation: 1763

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

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 1

Keith
Keith

Reputation: 24191

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

Upvotes: 1

dave
dave

Reputation: 64657

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)

Upvotes: 6

Related Questions