Reputation: 19341
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]);
Upvotes: 0
Views: 94
Reputation: 346
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]);
Upvotes: 0
Reputation: 387
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
Upvotes: 0
Reputation: 782489
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]);
Upvotes: 1