将两个json部分组合成一个json对象

时间:2017-07-09 07:03:27

标签: javascript json

我想将topData和bottomData组合成completeData。

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",  
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = topData.concat(bottomData)

因为这些不是数组,所以concat不会在这里工作。

这可以在不进行foreach循环的情况下完成吗?

3 个答案:

答案 0 :(得分:1)

您可以使用Object.assign()来连接对象。

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

来自MDN

  

Object.assign()方法用于复制所有值   枚举从一个或多个源对象到目标的自有属性   宾语。它将返回目标对象。

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",  
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "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);

答案 1 :(得分:1)

您可以使用Object.assign



var topData = {
  "auth": "1vmPoG22V3qqf43mPeMc",
  "property": "ATL-D406",
  "status": 1,
  "user": "test001@aaa.com",
  "name": "Abraham Denson"
}

var bottomData = {
  "agent": "pusher@agent.com",
  "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)



 它返回目标对象,表示bottomData的属性将被添加到topData

答案 2 :(得分:0)

var completeData = {...topData, ...bottomData};

这是object spread syntax