Convert string to object array javascript

Posted on


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;


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"};


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.

Leave a Reply

Your email address will not be published. Required fields are marked *