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

130
Visualizações
Dinamically adding objects to an existing object, and adding key/value pairs to said object

I have an object which already has 3 objects inside it. I want to dynamically add objects to one of those objects inside the original object, and then add key/value pairs to these dynamically added objects.

const result = {
    AV: {},
    Furnaces: {},
    "Production Lines": {}
};

So, this is the existing object with the objects inside. I add key/value pairs dinamically to "AV" easily because its simply

result[AV]["New key"] = value;

But if I try to run through a loop of the furnace names and add key/value pairs to the new object with that furnace's name, like so:

for (let i = 0; i < furnaces.length; i++) { 

    let furnaceName = furnace[i];

    result["Furnaces"][furnaceName]["Raw Material"] = 5;

};

it throws an error

Cannot set property "Raw Material" of undefined to "270000"
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you can simply use Object.assign

Assuming you have array of furnaces. Try this,

  for (let i = 0; i < furnaces.length; i++) { 

    let furnaceName = furnaces[i];
    const rawMaterial = { 'RawMaterial': 5 }
    Object.assign(result.Furnaces, {[`${furnaceName}`]: rawMaterial })

};
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