galso
galso

Reputation: 25

key-value pair undefined in javascript

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?

Upvotes: 2

Views: 3702

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

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

Upvotes: 4

Related Questions