Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding objects to array object

I'm trying to add objects to an existing array if the condition is true.

Below is my code

RequestObj = [{
    "parent1": {
        "ob1": value,
        "ob2": {
            "key1": value,
            "key2": value
        },
    },
},
{
    "parent2": {
        "ob1": value,
        "ob2":{
            "key1":value,
            "key2": value
        }
    }
}]

Here I'm trying to add an object to the RequestObj array if the condition is true. I could do RequestObj.push(). But i don't know how to added in parent1 object.

if (key3 !== null) {
    // add this below object to parent1 object
    "ob3": {
        "key1": value,
        "key2": value
    }
}

I'm not able to find any solution. Please help

like image 384
arunkumar Avatar asked Sep 12 '26 14:09

arunkumar


1 Answers

The way to add an element to an array is to push it.

// Create new object
var newObject = {
    "ob3": {
        "key1": value,
        "key2": value
    }
};
// Add new object to array
RequestObj.push(newObject);

You can also directly push an object into the array without declaring a variable first:

// Add new object to array
RequestObj.push({
    "ob3": {
        "key1": value,
        "key2": value
    }
});

UPDATE

If you are not pushing into the array but adding a new property to an object inside the array, you need to know the position of the element inside the array, like RequestObj[0] for the first element.

Then within that element, you need to add a new property to the parent1 object (RequestObj[0].parent1):

RequestObj[0].parent1.ob3 = {
      "key1": "A",
      "key2": "B"
 };

var RequestObj = [{
  "parent1": {
    "ob1": "A",
    "ob2": {
      "key1": "B",
      "key2": "C"
    },
  },
  "parent2": {
    "ob1": "D",
    "ob2": {
      "key1": "E",
      "key2": "F"
    }
  }
}];

var key3 = 'somethingNotNull';

if (key3 !== null) {
  RequestObj[0].parent1.ob3 = {
      "key1": "A",
      "key2": "B"
  };
}
console.log(RequestObj);
like image 143
Sébastien Avatar answered Sep 14 '26 05:09

Sébastien