Home > front end >  Converting an object into a string
Converting an object into a string

Time:09-06

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"

CodePudding user response:

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)

CodePudding user response:

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]}
    
  
}, {})
const f = JSON.stringify(newObj) 
console.log(typeof f)

this will print you "string" to console :)

CodePudding user response:

Maybe this will help,

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

const objToString = Object.keys(object1)
  .reduce((prev, key, index) => prev   `${key}: ${object1[key] || "All"}, `, "")
  .slice(0, -2);

console.log(objToString);

// a: somestring, b: 42, c: All, d: All, e: All, f: Some

CodePudding user response:

you could write your own function to achieve this like

var  toString = function(object){
  if(object instanceof Object){
  let objkeys = Object.keys(object);
  let str = "";
  for(let k of objkeys){
    object[k]= object[k]==null?"all":object[k];
      if(str!="")
      str =", ";
      str =k   ":"   object[k];
  }
  return str;
}
return "";
}

will get you the desired result

  • Related