Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

327
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

you can try with the spread operator

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda