K
K
krslnkv2019-08-31 02:54:27
JavaScript
krslnkv, 2019-08-31 02:54:27

How to combine array and object in json?

At the moment there is an array cart, inside of which there are objects. The array needs to be converted to a json object, but after performing the operation, an object is created with a single key, in which the last element of the array is written

var cart = [];
var orderDetail1 = {
            dishId: 1,
            price: 200,
            quantyty: 1,
        }
var orderDetail2 = {
            dishId: 2,
            price: 150,
            quantyty: 4,
        }
var order = {
                    tableId: 1,
                    shiftId: 5,
                    finalPrice: 800
                }
cart.push(orderDetail1 );
cart.push(orderDetail2 );

At the output, I try to get a JSON object of the following form:
{
"order" : {
      "tableId" : 1 ,
      "shiftId" :  5,
      "finalPrice": 800
    },
"orderDetails" : [
    {
      "dishId" : 1,
      "price" : 200,
      "quantyty": 1
    },
    {
      "dishId" : 2,
      "price" : 150,
      "quantyty": 4
    },
  ]
}

I can't figure out how to combine an array and an object into one JSON

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2019-08-31
@krslnkv

var json = JSON.stringify({
  order: order,
  orderDetails: cart
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question