Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading