How can I concat two objects?

Viewed 79

My script JavaScript like this:

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

I want to concat the objects. So I want the result like this:

enter image description here

How can I do it?

3 Answers

You can use dot-syntax and the = operator to set a property of the customer object:

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)

If you don't want customer to be changed, you can use the spread syntax instead:

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)

You can set the property directly in customers:

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}
];

Object.assign would do the trick: customer = Object.assign(customer, { products: products })

Related