moses toh
moses toh

Reputation: 13162

How can I combine two object in javascript?

my first object like this :

{id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}

my second object like this :

{data: {id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}, expired: "2017-08-16T06:46:02.566Z"}

I want to combine the object

How can I do it?

Upvotes: 0

Views: 152

Answers (2)

Suman r
Suman r

Reputation: 75

we can use the Object.assign(obj1, obj2); function to merge or else please add the sample output format you are expecting

var x={id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}

var y={data: {id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}, expired: "2017-08-16T06:46:02.566Z"}

var z = Object.assign(x, y);

console.log(z)
console.log(z.id)
console.log(z.data)
console.log(z.data.id)
 

Upvotes: 0

BradLaney
BradLaney

Reputation: 2413

How can I merge properties of two JavaScript objects dynamically?

This method can combine the properties of two objects together.

Object.assign(obj1, obj2);

Or you have to change your data structure, if you're thinking about arrays.

var x = {id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}

and

var y = {data: [{id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}], expired: "2017-08-16T06:46:02.566Z"}

Then you

y.data.push(x)

Upvotes: 2

Related Questions