0

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!

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

you can try with the spread operator

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

Comments

1

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.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.