Usama Liaqat
Usama Liaqat

Reputation: 29

Javascript How to push a key value pair into a nested object array

I have this JSON response where I want to push "status": "pending", inside the nested Menu array, Please help how I can achieve this in Javascript.

[
{
    "id": 1,
    "status": "pending",
    "menues": [
        {
            "title": "Coke",
            "price": "200"
        }
    ]
},
{
    "id": 2,
    "status": "delivered",
    "menues": [
        {
            "title": "Pepsi",
            "price": "120"
        }
    ]
}
]

Here is what I want to achieve: I just want to push the Staus key/value inside the Menu array

[
{
    "id": 1,
    "menues": [
        {
            "title": "Coke",
            "price": "200",
            "status": "pending",
        }
    ]
},
{
    "id": 2,
    "menues": [
        {
            "title": "Pepsi",
            "price": "120",
            "status": "delivered",
        }
    ]
}
] 

Upvotes: 0

Views: 1487

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Maybe this is what you want? The following script creates a new nested array structure, leaving the original unchanged. Instead of deleting the status property from the outer object I limit the creation of properties in the newly created object to id and menues.

I changed this answer in response to OP's comment asking for ES5 and ES6 methods and the ... operator.

arr = [
  {
      "id": 1,
      "status": "pending",
      "menues": [
          {
              "title": "Coke",
              "price": "200"
          }
      ]
  },
  {
      "id": 2,
      "status": "delivered",
      "menues": [
          {
              "title": "Pepsi",
              "price": "120"
          }
      ]
  }
];

const res=arr.map(nested =>({ id:nested.id, menues:
  nested.menues.map(menu =>({...menu,status:nested.status})) }));
console.log(res);

Upvotes: 0

Mureinik
Mureinik

Reputation: 311326

You can go over the array, and for each item, go over the items in menues. Using the forEach method, this can even be done as a single statement:

arr = [
  {
      "id": 1,
      "status": "pending",
      "menues": [
          {
              "title": "Coke",
              "price": "200"
          }
      ]
  },
  {
      "id": 2,
      "status": "delivered",
      "menues": [
          {
              "title": "Pepsi",
              "price": "120"
          }
      ]
  }
];

arr.forEach(nested => {
    nested.menues.forEach(menu => menu.status = nested.status);
    delete nested.status
});
console.log(arr);

Upvotes: 1

Related Questions