2

I've apologize if this is a trivial task, and I've also been googling and searching high and low for some solution I can get my head around but so far no dice. So anyways....

I have this:

var myList = "key1,value1,key2,value2"

And I want to populate a struct with this string so I can reference it like this:

alert(myList.key1)  // displays value1

Thoughts? There's probably some way to do this with JQuery's .each() perhaps? I'm seriously lost either way! Maybe just because it's really late and I've been stumbling through familiarizing myself with JS and JQuery again after a long hiatus. Any help is appreciated!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Alec
  • 21
  • 1
  • Have a look at [this question](http://stackoverflow.com/q/8751034/218196). You just have to create the array, which is easily done via `.split()`. – Felix Kling Jan 08 '12 at 09:13

2 Answers2

5

Assuming you never have commas in the values, you could start by using split:

var parts = myList.split(",");// ["key1", "value1", ...]

From there you can just use a simple loop:

var obj = {};
for (var i = 0; i < parts.length; i+=2) obj[parts[i]] = parts[i + 1];

As this answer points out, you can also write the loop like this:

var obj = {};
while (parts.length) obj[parts.shift()] = parts.shift();

This is a neat way to write this, but behaves differently: after this loop, parts will be empty.

Community
  • 1
  • 1
Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
  • 1
    Also have a look at [this answer](http://stackoverflow.com/a/8751218/990877), which offers a very elegant elegant solution using [`Array.shift()`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift). – Peter-Paul van Gemerden Jan 08 '12 at 12:55
2

String.replace method is your first choice when it comes to string parsing tasks

var myList = "key1,value1,key2,value2"
var result = {}

myList.replace(/(\w+),(\w+)/g, function($0, $1, $2) {
    result[$1] = $2
})
georg
  • 211,518
  • 52
  • 313
  • 390