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

115
Vistas
Looping over an object to change values inside

I am trying to send an object to an api and my object contains arrays that I want to turn into strings. However I am having trouble returning the new object with the arrays turned to strings. My goal is to have a copy of the original object with all the arrays turned into strings.

const object1 = {
  a: ["TX", "CA", "LA"],
  b: 42,
  c: false
  d: []
};

for (const [key, value] of Object.entries(object1)){
  if(Array.isArray(object1[key]) && object1[key].length > 0){
   object1[key].toString()
  }
}
console.log(object1)
//returns the original object without `a` as string
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are not assigning the new value to anything, so it is being lost with each loop. Try:

object1[key] = object1[key].toString()

const object1 = {
  a: ["TX", "CA", "LA"],
  b: 42,
  c: false,
  d: []
};

for (const [key, value] of Object.entries(object1)){
  if(Array.isArray(object1[key]) && object1[key].length > 0){
   object1[key] = object1[key].toString()
  }
}
console.log(object1)
//returns the original object without `a` as string

This way with every for loop, you reassign object1[key] to object1[key].toString()

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use join on the arrays to form strings.

const object1 = {
  a: ["TX", "CA", "LA"],
  b: 42,
  c: false,
  d: []
};

for (const [key, value] of Object.entries(object1)){
  if(Array.isArray(value)) {
    object1[key] = value.join(',');
  }
}
console.log(object1)

If you need to get arrays back later, use split.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should use join(",")

const object1 = {
 a: ["TX", "CA", "LA"],
 b: 42,
 c: false,
 d: []
};

 for (const [key, value] of Object.entries(object1)){
  if(Array.isArray(object1[key]) && object1[key].length > 0){
   object1[key] = object1[key].join(",")
 }
}
console.log(object1)
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