1
\$\begingroup\$

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, to me it 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]);

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This can be simplified by using destructuring assignment into an array, followed by simple assignment into the object obj. While it may not be much more efficient it can eliminate the need to use the forEach method.

const val = "someValue,display";
const [columnVal, displayValue] = val.split(",");
const obj = {columnVal, display: displayValue === "display"};

console.log([obj]);

The variable name obj isn't very descriptive but there isn't much context about how it is used.

A good habit and recommendation of many style guides is to use strict equality operators (i.e. ===, !==) whenever possible (like is used in the snippet above). The problem with loose comparisons is that it has so many weird rules one would need to memorize in order to be confident in its proper usage.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.