Search code examples
javascriptarraysobjecttostring

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

Solution

  • 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()