[javascript] String to object in JS

I have a string as

string = "firstName:name1, lastName:last1"; 

now I need one object obj such that

obj = {firstName:name1, lastName:last1}

How can I do this in JS?

This question is related to javascript string object

The answer is


You need use JSON.parse() for convert String into a Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

This simple way...

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);

output

name1

if you're using JQuery:

var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg

REMEMBER: eval is evil! :D


In your case

var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
    KeyVal[i] = KeyVal[i].split(":");
    obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}

Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.

_x000D_
_x000D_
var obj = '{ firstName:"John", lastName:"Doe" }';_x000D_
_x000D_
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {_x000D_
  return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';_x000D_
});_x000D_
_x000D_
obj = JSON.parse(jsonStr); //converts to a regular object_x000D_
_x000D_
console.log(obj.firstName); // expected output: John_x000D_
console.log(obj.lastName); // expected output: Doe
_x000D_
_x000D_
_x000D_

This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.

_x000D_
_x000D_
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"]  }}';_x000D_
_x000D_
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {_x000D_
  return '"' + s.substring(0, s.length-1) + '":';_x000D_
});_x000D_
_x000D_
var obj = JSON.parse(jsonStr);_x000D_
console.log(obj.favorites.movies[0]); // expected output: star wars
_x000D_
_x000D_
_x000D_


var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";    

var initial_arr_objects = stringExample.split("|");
    var objects =[];
    initial_arr_objects.map((e) => {
          var string = e;
          var fields = string.split(','),fieldObject = {};
        if( typeof fields === 'object') {
           fields.forEach(function(field) {
              var c = field.split(':');
              fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
           });
        }
            console.log(fieldObject)
            objects.push(fieldObject);
        });

"objects" array will have all the objects


Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

If you have a string like foo: 1, bar: 2 you can convert it to a valid obj with:

str
  .split(',')
  .map(x => x.split(':').map(y => y.trim()))
  .reduce((a, x) => {
    a[x[0]] = x[1];
    return a;
  }, {});

Thanks to niggler in #javascript for that.

Update with explanations:

const obj = 'foo: 1, bar: 2'
  .split(',') // split into ['foo: 1', 'bar: 2']
  .map(keyVal => { // go over each keyVal value in that array
    return keyVal
      .split(':') // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  })
  .reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(),
    // first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1')
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log(obj)

Confusing MDN docs:

Demo: http://jsbin.com/hiduhijevu/edit?js,console

Function:

const str2obj = str => {
  return str
    .split(',')
    .map(keyVal => {
      return keyVal
        .split(':')
        .map(_ => _.trim())
    })
    .reduce((accumulator, currentValue) => {
      accumulator[currentValue[0]] = currentValue[1]
      return accumulator
    }, {})
}

console.log(str2obj('foo: 1, bar: 2')) // see? works!

I know this is an old post but didn't see the correct answer for the question.

var jsonStrig = '{';
      var items = string.split(',');
      for (var i = 0; i < items.length; i++) {
          var current = items[i].split(':');
          jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
      }
      jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
      jsonStrig += '}';
var obj = JSON.parse(jsonStrig);
console.log(obj.firstName, obj.lastName);

Now you can use obj.firstName and obj.lastName to get the values as you could do normally with an object.


Actually, the best solution is using JSON:

Documentation

JSON.parse(text[, reviver]);

Examples:

1)

var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'

2)

var myobj = JSON.parse(JSON.stringify({
    hello: "world"
});
alert(myobj.hello); // 'world'

3) Passing a function to JSON

var obj = {
    hello: "World",
    sayHello: (function() {
        console.log("I say Hello!");
    }).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();

I'm using JSON5, and it's works pretty well.

The good part is it contains no eval and no new Function, very safe to use.


string = "firstName:name1, lastName:last1";

This will work:

var fields = string.split(', '),
    fieldObject = {};

if( typeof fields === 'object') ){
   fields.each(function(field) {
      var c = property.split(':');
      fieldObject[c[0]] = c[1];
   });
}

However it's not efficient. What happens when you have something like this:

string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";

split() will split 'http'. So i suggest you use a special delimiter like pipe

 string = "firstName|name1, lastName|last1";


   var fields = string.split(', '),
        fieldObject = {};

    if( typeof fields === 'object') ){
       fields.each(function(field) {
          var c = property.split('|');
          fieldObject[c[0]] = c[1];
       });
    }

Here is my approach to handle some edge cases like having whitespaces and other primitive types as values

const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name "; 

const strToObj = str
  .trim()
  .split(",")
  .reduce((acc, item) => {
    const [key, val = ""] = item.trim().split(":");
    let newVal = val.trim();

    if (newVal == "null") {
      newVal = null;
    } else if (newVal == "undefined") {
      newVal = void 0;
    } else if (!Number.isNaN(Number(newVal))) {
      newVal = Number(newVal);
    }else if (newVal == "true" || newVal == "false") {
      newVal = Boolean(newVal);
    }
    return { ...acc, [key.trim()]: newVal };
  }, {});

This is universal code , no matter how your input is long but in same schema if there is : separator :)

var string = "firstName:name1, lastName:last1"; 
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
  var b = i + 1, c = b/2, e = c.toString();
     if(e.indexOf('.') != -1 ) {
     empty[el] = arr[i+1];
  } 
}); 
  console.log(empty)

If I'm understanding correctly:

var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
    var tup = property.split(':');
    obj[tup[0]] = tup[1];
});

I'm assuming that the property name is to the left of the colon and the string value that it takes on is to the right.

Note that Array.forEach is JavaScript 1.6 -- you may want to use a toolkit for maximum compatibility.


I implemented a solution in a few lines of code which works quite reliably.

Having an HTML element like this where I want to pass custom options:

<div class="my-element"
    data-options="background-color: #dadada; custom-key: custom-value;">
</div>

a function parses the custom options and return an object to use that somewhere:

function readCustomOptions($elem){
    var i, len, option, options, optionsObject = {};

    options = $elem.data('options');
    options = (options || '').replace(/\s/g,'').split(';');
    for (i = 0, len = options.length - 1; i < len; i++){
        option = options[i].split(':');
        optionsObject[option[0]] = option[1];
    }
    return optionsObject;
}

console.log(readCustomOptions($('.my-element')));