I want to convert string to object array. Suppose I have following string.
const str = "someValue,display";
I want to convert it like following.
[{ columnVal: "someValue", display: true }]
if it’s display then I want value as true if noDisplay then false.
I tried following but, doesn’t seems like best solution.
const val = "someValue,display"; const obj = {}; val.split(",").forEach((str, index) => { if(index === 0) { obj.columnVal = str; } else { if(str == "display") { obj.display = true; } else { obj.display = false; } } }) console.log([obj]);
Advertisement
Answer
Using a loop when you want to do something with specific indexes seems wrong. Just access the elements you want and set the appropriate object properties.
const val = "someValue,display"; const vals = val.split(","); const obj = { columnVal: vals[0], display: vals[1] == "display" }; console.log([obj]);