简体   繁体   中英

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?

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)

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) 

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