Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two json sections into one json object [duplicate]

I would like to combine topData and bottomData into completeData.

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",  
    "status" : 1,
    "user" : "[email protected]",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "[email protected]",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = topData.concat(bottomData)

Since these are not arrays, concat wont work here.

Can this be done without making foreach loops?

like image 313
torbenrudgaard Avatar asked Jul 09 '17 07:07

torbenrudgaard


2 Answers

You can use Object.assign() to concatenate your objects.

var newObj = Object.assign({}, topData, bottomData)

From MDN:

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.


var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",  
    "status" : 1,
    "user" : "[email protected]",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "[email protected]",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = Object.assign({}, topData, bottomData);

console.log(completeData);
like image 120
Mr. Alien Avatar answered Nov 09 '22 10:11

Mr. Alien


You can use Object.assign.

var topData = {
  "auth": "1vmPoG22V3qqf43mPeMc",
  "property": "ATL-D406",
  "status": 1,
  "user": "[email protected]",
  "name": "Abraham Denson"
}

var bottomData = {
  "agent": "[email protected]",
  "agency": "Thai Tims Agency",
  "agentCommission": 1000,
  "arrival": "arrive 12pm at condo",
  "departure": "leaving room at 6pm",
}

var completeData = Object.assign(topData, bottomData);
console.log(completeData)
It return the target object which mean properties from bottomData will be added to topData
like image 2
brk Avatar answered Nov 09 '22 09:11

brk