Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
How to push array containts objects to object with key using Javascript?

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

you can try with the spread operator

obj['level'].push(...arrObj);
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!