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

189
Visualizações
problems filling an array with javascript

I parsed a json and I'm trying to take 2 values for each element from the json and put them in a array the problem is that I want to put the values into the array like a single element "array" example:

[
 { name: 'name1', elements: [ 'elem1' ] },
 { name: 'name2', elements: [ 'elem2', 'elem3' ] }
]

I tried 2 ways.

the first is this:

function getMonsters(json) {
    var monsters = [];
    var monster = {};
    json.forEach(element => {
        if (element.type === "large") {
            monster['name'] = element.name;
            monster['elements'] = element.elements;
            monsters.push(monster);
        }
    });
    return monsters;
}

the problem with the first way is that it always returns the same 2 values: response image

the second way is this:

function getMonsters(json) {
    var monsters = [];
    var monster = {};
    json.forEach(element => {
        if (element.type === "large") {
            monsters.push(element.name, element.elements);
        }
    });
    return monsters;
}

but the problem with the second way is that it returns each monster and element separately and not like in my example: response image

this is the json if u want to check : https://mhw-db.com/monsters

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are reusing the monster object every iteration in your first example. Either move the declaration of var monster = {} into the loop or, better yet, just push an object literal.

function getMonsters(json) {
  const monsters = [];

  json.forEach(({ elements, name, type }) => {
    if (type === "large") {
       monsters.push({ name, elements });
    }
  });

  return monsters;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Your first attempt is almost correct. The reason why all of the items in the array end up being the same object is because monster is the same reference in all of the array items. You need a new instance of monster on every iteration. Just put your initialization of monster in your loop

function getMonsters(json) {
var monsters = [];
json.forEach(element => {
    if (element.type === "large") {
        var monster = {};
        monster['name'] = element.name;
        monster['elements'] = element.elements;
        monsters.push(monster);
    }
});
return monsters;
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