String to object in JS

JavascriptStringObject

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Actually, the best solution is using JSON:

Documentation

JSON.parse(text[, reviver]);

Examples:

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

Solution 2 - Javascript

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

This should work then:

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

This simple way...

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

output

name1

Solution 5 - Javascript

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.

var obj = '{ firstName:"John", lastName:"Doe" }';

var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
  return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});

obj = JSON.parse(jsonStr); //converts to a regular object

console.log(obj.firstName); // expected output: John
console.log(obj.lastName); // expected output: Doe

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.

var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"]  }}';

var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {
  return '"' + s.substring(0, s.length-1) + '":';
});

var obj = JSON.parse(jsonStr);
console.log(obj.favorites.movies[0]); // expected output: star wars

Solution 6 - Javascript

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!

Solution 7 - Javascript

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

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Solution 12 - Javascript

In your case, The short and beautiful code

Object.fromEntries(str.split(',').map(i => i.split(':')));

Solution 13 - Javascript

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)

Solution 14 - Javascript

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 };
  }, {});

Solution 15 - Javascript

const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhijibijiView Question on Stackoverflow
Solution 1 - JavascriptMatejView Answer on Stackoverflow
Solution 2 - JavascriptPhilippe LeybaertView Answer on Stackoverflow
Solution 3 - JavascriptcdlearyView Answer on Stackoverflow
Solution 4 - JavascriptWianto WieView Answer on Stackoverflow
Solution 5 - JavascriptFaisal ChishtiView Answer on Stackoverflow
Solution 6 - JavascriptcorysimmonsView Answer on Stackoverflow
Solution 7 - JavascriptGrigorAtaryanView Answer on Stackoverflow
Solution 8 - JavascriptmzalazarView Answer on Stackoverflow
Solution 9 - JavascriptroduView Answer on Stackoverflow
Solution 10 - JavascriptEmeka MbahView Answer on Stackoverflow
Solution 11 - JavascriptJames YangView Answer on Stackoverflow
Solution 12 - JavascriptbenView Answer on Stackoverflow
Solution 13 - JavascriptpanatoniView Answer on Stackoverflow
Solution 14 - JavascriptAkash SinghView Answer on Stackoverflow
Solution 15 - JavascriptsoliceView Answer on Stackoverflow
Solution 16 - JavascriptVahag ChakhoyanView Answer on Stackoverflow
Solution 17 - JavascriptAdityaKapreShrewsburyBostonView Answer on Stackoverflow
Solution 18 - JavascriptRaoulView Answer on Stackoverflow