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]);
asked Sep 16, 2021 at 16:34
ketan
19.4k42 gold badges68 silver badges107 bronze badges
3 Answers 3
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]);
answered Sep 16, 2021 at 16:46
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Sebastian Simon
Even more compact would be destructuring:
const [ columnVal, display ] = val.split(",");, { columnVal, display: display === "display" }.TR3
^^^ I'd prefer this solution over mine, you'd just need to assign the object to a variable.
You're basically there, you just don't need to loop through it.
const obj = {}
const strArr = str.split(",")
obj.display = strArr.includes("display")
obj.columnVal = strArr[0] // as long as this never changes
Comments
you dont need loop on it, I think this is more effective way
const str = "someValue,display",obj = {};
arr = str.split(",");
obj.columnVal = arr[0];
obj.display = arr === "display";
console.log([obj]);
answered Sep 16, 2021 at 17:01
trysetyoutomo
3462 silver badges8 bronze badges
Comments
lang-js
else if, or to useobj.display = str === "display". Note that code review questions should go on Code Review.obj.display=str === "display";