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

175
Visualizações
for loop gives only last value in javascript

I have created variable outside to get values from inside but I only get last value in both variables.

var categoryProductid;
var PPProducttitle;

for (var key in UpdatedCategory) {

  const actual = UpdatedCategory[key]
  var categoryProductid = actual.id;
  var PPProducttitle = actual.title;

  console.log(PPProducttitle)
  console.log(categoryProductid)
}

console.log(PPProducttitle)
console.log(categoryProductid)

when I do console.logs() from inside and outside of for loop I get two different values.

Any help will be appreciated thank you!!!!!

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

0

I'm going to assume that UpdatedCategory is an object (if it's an array, please see my answer here for what to use instead of for-in to loop through it).

The basic problem with that code is that you're assigning to the same variable over and over. The reason it's the same variable is that var doesn't have block scope, so the var part of var categoryProductid = actual.id; is completely ignored (and similar for var PPProducttitle = actual.title;). Instead, you're reusing the variables you declared prior to the for loop.

A variable can only hold one value, so when you assign a new value to it, it no longer holds the old value.

If you want to hold multiple values with a variable, you can assign a container to it that can hold multiple values, such as an array, an object, a Map, or a Set.

You haven't said what end result you want, but here's an example that creates two arrays and fills them with the id and title of the products from UpdatedCategory:

// Again, I'm assuming `UpdatedCategory` is an object:
const UpdatedCategory = {
    a: {
        id: 1,
        title: "a",
    },
    b: {
        id: 2,
        title: "b",
    },
    c: {
        id: 3,
        title: "c",
    },
};

// `[]` creates a new empty array.
// We can use `const` to declare these because we never change their
// value (they only ever refer to a single array), but you could use
// `let` if you preferred. Don't use `var` in new code, it's deprecated.
// Note: I've renamed these slightly to:
// 1. Stick to standard naming conventions
//     * Initial capitals are used primarily for constructor functions
//     * Variables referring to arrays are generally plurals
// 2. Be consistent in capitalization
const categoryProductIds = [];
const ppProductTitles = [];

for (var key in UpdatedCategory) {
    // Get this property value
    const actual = UpdatedCategory[key];

    // Push the `id` and `title` into the relevant arrays
    categoryProductIds.push(actual.id);
    ppProductTitles.push(actual.title);
}

// Show the contents of the arrays
console.log(ppProductTitles);
console.log(categoryProductIds);

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