Search code examples
javascriptarraysstringobjecttostring

Converting an object into a string


I need to iterate over an object turn all values that are falsey to "All" and turn that Object into a string.

I thought I could use .reduce to replace the falsey values and that works. But I am having trouble figuring out a clean way to have the object with each key value pair as its own string separated by commas.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false,
  d: null,
  e: 0,
  f: "Some"
};

let newObj = Object.keys(object1).reduce((acc, key) => {
    
  if(!object1[key]){
    object1[key] = "All"
  }
  
  return {...acc, [key]: object1[key]}
    
  
}, {})

console.log(Object.entries(newObj).join(":"));

my expected Result would be "a: somestring, b: 42, c: All, d: All, e:All, f:Some"


Solution

  • you should do something like this

    const object1 = {
      a: 'somestring',
      b: 42,
      c: false,
      d: null,
      e: 0,
      f: "Some"
    };
    
    const string = Object.entries(object1).map(([k, v]) => `${k}: ${v? v: 'All'}`).join(',')
    
    console.log(string)