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

78
Vistas
Traversing Arrays by forEach

Trying to traverse an array into an object with key/pair (yes I know of reduce):

This is the array:

filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]

But for some reason when I do forEach:

filtered2.forEach( (indiv) => {
  console.log([indiv[0]]+" | " +[indiv[1]])
    obj3 = {
      ...obj3,
      [[indiv[0]][0]]  : [indiv[1]]
    }
})

Console.log will see each (indiv) as "hwModelName | TestHwModel03" at [indiv[0]]+" | " +[indiv[1]], so both are basic strings

But the forEach function sees [indiv[1]] as Array ["TestHwModel03"] So I have to go one more depth level [indiv[1]][0] into the array to get the unwrapped string "TestHwModel03"

Why there this difference?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Remove the square brackets surrounding the value.

filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]

let obj3 = {}

filtered2.forEach( (indiv) => {
    obj3 = {
      ...obj3,
      [indiv[0]]  : indiv[1]
    }
})

console.log(obj3)

Although it's much simpler to use Object.fromEntries:

filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]

let obj3 = Object.fromEntries(filtered2)
console.log(obj3)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use reduce method on an array to convert the array to a map. Or You can use Object.fromEntries if your env supports the latest version of ES2017.

filtered2 = [
  ["deviceName", "TestDevice00003"],
  ["hwModelName", "TestHwModel03"],
  ["deviceTypeName", "TestDeviceType03"],
  ["serviceTag", "A1A03"],
];
const toMap = (arr = []) =>
  arr.reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
  }, {});

console.log(toMap(filtered2))

/// Other way
console.log(Object.fromEntries(filtered2))

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