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

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

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