简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM