Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

you can try with the spread operator

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda