代码之家  ›  专栏  ›  技术社区  ›  Success Man

我怎样才能把两个物体连在一起?

  •  3
  • Success Man  · 技术社区  · 6 年前

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

    我想把这些东西粘起来。所以我想要这样的结果:

    enter image description here

    3 回复  |  直到 6 年前
        1
  •  5
  •   Luca Kiebel    6 年前

    可以使用点语法和 = 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)

    如果你不想

    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)
        2
  •  0
  •   sagi    6 年前

    您可以直接在客户中设置属性:

    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}
    ];
    
        3
  •  0
  •   Daniel    6 年前

    customer = Object.assign(customer, { products: products })