Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!