我的脚本JavaScript是这样的:
<script>
var customer = {"name":"John", "address":'London'};
var products = [
{"product_name":"clothes", "quantity":1, "price":1000},
{"product_name":"trousers", "quantity":1, "price":500},
{"product_name":"shoes", "quantity":1, "price":2000}
];
</script>
我想连接对象。所以我想要这样的结果:
我该怎么办?
答案 0 :(得分:5)
您可以使用点语法和=
运算符来设置customer
对象的属性:
var customer = {"name":"John", "address":'London'};
var products = [
{"product_name":"clothes", "quantity":1, "price":1000},
{"product_name":"trousers", "quantity":1, "price":500},
{"product_name":"shoes", "quantity":1, "price":2000}
];
customer.products = products;
console.log(customer)
如果您不想更改customer
,则可以使用传播语法:
var customer = {"name":"John", "address":'London'};
var products = [
{"product_name":"clothes", "quantity":1, "price":1000},
{"product_name":"trousers", "quantity":1, "price":500},
{"product_name":"shoes", "quantity":1, "price":2000}
];
const customerAndProducts = { ...customer, products : products }
console.log(customer)
console.log(customerAndProducts)
答案 1 :(得分:0)
您可以直接在客户中设置属性:
var customer = {"name":"John", "address":'London'};
customer.products = [
{"product_name":"clothes", "quantity":1, "price":1000},
{"product_name":"trousers", "quantity":1, "price":500},
{"product_name":"shoes", "quantity":1, "price":2000}
];
答案 2 :(得分:0)
Object.assign可以解决问题:customer = Object.assign(customer, { products: products })