This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?

(66个答案)


3年前关闭。




我想将topData和bottomData合并为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)

由于这些不是数组,因此concat在这里不起作用。

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

最佳答案

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

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

MDN:





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

10-06 07:54