0

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]);

4
  • What is wrong with this solution? The only thing I could think of would be to either merge the else if, or to use obj.display = str === "display". Note that code review questions should go on Code Review. Commented Sep 16, 2021 at 16:38
  • you want make shorter code ? Commented Sep 16, 2021 at 16:41
  • Is there always a second element in the string? Commented Sep 16, 2021 at 16:43
  • you can completely avoid the inner if else statement by obj.display=str === "display"; Commented Sep 16, 2021 at 16:47

3 Answers 3

1

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]);

Sign up to request clarification or add additional context in comments.

2 Comments

Even more compact would be destructuring: const [ columnVal, display ] = val.split(",");, { columnVal, display: display === "display" }.
^^^ I'd prefer this solution over mine, you'd just need to assign the object to a variable.
0

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

0

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.