Home > front end >  How to push array containts objects to object with key using Javascript?
How to push array containts objects to object with key using Javascript?

Time:06-17

I have created an object like this:

var obj = {
    name: $('#name').val(),
    age:  $('age').val()
};

And I have an array object like this

var arrObj = [
    {level: 10, status: 1},
    {level: 8, status: 0}
];

I want to push my array to an object with a defined key, and expected result:

{
    name: 'Name A',
    age:  30,
    level: [
        {level: 10, status: 1},
        {level: 8, status: 0}
    ]
}

But I don't know how to push my array to object with a key. I tried:

var obj = {
    name: $('#name').val(),
    age:  $('age').val(),
    level: []
};

obj['level'].push(arrObj);

But I will make my level element have 1 more array level like this:

{
    name: 'Name A',
    age:  30,
    level:[ 
        [
            {level: 10, status: 1},
            {level: 8, status: 0}
        ]
    ]
}

How I can get the results I expected.

Thank you very much!

CodePudding user response:

An array can be directly assigned to an object using = (assignment operator)

You can try out assigning an array of objects to the level key by following.

var obj = {
    name: 'Name A',
    age:  30,
    level: []
};
var arrObj = [
    {level: 10, status: 1},
    {level: 8, status: 0}
];

obj.level = arrObj //arrObj's value will be overwritten to level key and if such key doesn't exist then it'll be created!

console.log(obj)

CodePudding user response:

you can try with the spread operator

obj['level'].push(...arrObj);

CodePudding user response:

You can just do this

obj.level = arrObj;

The level property within obj will be created on the fly if such property doesn't exist.

CodePudding user response:

You can use concat in place of push:

var obj = {
    name: 'Name A',
    age:  30,
    level: []
};
var arrObj = [
    {level: 10, status: 1},
    {level: 8, status: 0}
];

obj.level = obj.level.concat(arrObj);

console.log(obj)

  • Related