Home > Back-end >  How to insert an object into an array which is inside an object?
How to insert an object into an array which is inside an object?

Time:12-15

Suppose if we are having data like this, how can we use dot notations or anything to update the array(data2) inside the object data1 which is inside the array(data).

data = [
data1:
    {
        a:"1",
        b:"2"
    }
]

    // another array(data2 - below) I am having I have to push that array inside 
    data1 as an object
data2 = [
    {
        c:"3"
    },
    {
        d:"4"
    }
    ]

The response I want as below:

    data = [
data1:
    {
        a:"1",
        b:"2"
    },
data2 = [
    {
        c:"3"
    },
    {
        d:"4"
    }
  ]
]

CodePudding user response:


var array = [];

array['data1'] = { 'name': 'a' }

var array2 = [{ c: 3 }, { d: 4 }];

array['data2'] = array2;

console.log(array)

OutPut:

[ data1: { name: 'a' }, data2: [ { c: 3 }, { d: 4 } ] ]

CodePudding user response:

I didnt really understand your question but i think this is what you want?!

data = {
    data1:
    {
        a: "1",
        b: "2"
    }
}
data2 = [
    {
        c: "3"
    },
    {
        a: "3"
    },
    {
        d: "4"
    }
]

for (var key in data2) {
    for (var key2 in data2[key]) {
        if(data.data1[key2] != null){
            console.log("data.data1 with they key"   key2   " could have been replaced/updated with "   data2[key][key2]);
        }
        console.log("key "   key2   " has value "   data2[key][key2]);
    }
}

Result:

key c has value 3 data.data1 with they keya could have been replaced/updated with 3 key a has value 3 key d has value 4

Edit:

Why dont you just do

data["data2"] = data2?
  • Related