arunkumar
arunkumar

Reputation: 353

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

Upvotes: 3

Views: 3923

Answers (2)

Karabah
Karabah

Reputation: 249

You shoud iterate RequestObj in loop and find object by key parent1.

For that you can use .filter function like this:

for(let i = 0; i < RequestObj.lenght; i++) {
   let found_object = RequestObj[i].filter(function (r) {
      return r == 'parent1'
   });
}

Then you can execute operations over found_object.

Upvotes: 0

S&#233;bastien
S&#233;bastien

Reputation: 12139

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

Upvotes: 3

Related Questions