2

For some reason I have a string like this:

"id: 123, title: something, category: science, ... "

To make a javascript object containing the key-value pairs I wrote the following method:

function stringToMap(stringToCut){
    var map = {};
    var listOfPairs = stringToCut.split(",");
    for(var i = 0; i < listOfPairs.length; i++){
        var pair = listOfPairs[i].split(":");
        map[pair[0]] = pair[1];
    }

    return map;

}

it's important to access it with dot, not with [] brackets. In chrome debug mode I see the expected object, but when I want to access one of it's element, like:

console.log(obj.title);

I get undefined...

What Am I doing wrong?

1 Answer 1

4

It's because there's a space in your key name:

console.log(obj[" title"]); // "something"

To fix this, change your first split to split on ", " instead of just ",":

var listOfPairs = stringToCut.split(", ");

JSFiddle demo.

As a further fix, you'll also want to change your second split to split on ": " rather than just ":", otherwise all your values will begin with spaces.

var pair = listOfPairs[i].split(": ");
2
  • Mind the space in the beginning. console.log(obj["title"].trim()); Nov 27, 2013 at 9:46
  • Indeed, that space was the problem. Thanks a lot!
    – galso
    Nov 27, 2013 at 9:54

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.