如何在javascript中组合两个对象?

时间:2017-08-16 06:19:56

标签: javascript jquery arrays object

我的第一个对象是这样的:

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

我的第二个对象是这样的:

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

我想组合对象

我该怎么做?

2 个答案:

答案 0 :(得分:2)

How can I merge properties of two JavaScript objects dynamically?

此方法可以将两个对象的属性组合在一起。

value

如果您正在考虑数组,则必须更改数据结构。

local gumbo = require "gumbo"

local input = [[
<div class="login-fields">
    <label id="username-lbl" for="username" class="">User Name</label>
    <input type="text" name="username" id="username" value="test" class="validate-username" size="25"/>
</div>
]]

local document = assert(gumbo.parse(input))
local element = assert(document:getElementById("username"))
element:setAttribute("value", "")
local output = assert(document:serialize())
io.write(output, "\n")

Object.assign(obj1, obj2);

然后你

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

答案 1 :(得分:0)

我们可以使用Object.assign(obj1,obj2);要合并的功能,否则请添加您期望的样本输出格式

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)