2

I'm trying to convert a delimited key/value string into an object in javascript and finding my javascript-fu lacking.

I have something like:

"rating:1,2,3"

and I'd like to turn it into something like

{rating: [1,2,3]}

Anyone know how to accomplish this

1
  • If the string is in JSON format, you can use JSON.parse. Commented Oct 20, 2011 at 18:18

1 Answer 1

3
var str = "rating:1,2,3";
var splitStr = str.split(":");

var obj = {};
obj[splitStr[0]] = splitStr[1].split(",").map(function(value) {return parseInt(value, 10)});
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this will give {rating:["1","2","3"]} rather than {rating:[1,2,3]}.
This is way more elegant then what i ended up coming up with. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.