David David - 1 day ago 4
Javascript Question

How to create an object/array from a key/value string made up with '/'

Take the following string:

/foo/1/bar/2/cat/bob


I need to parse this into an object or array which ends up being:

foo = 1
bar = 2
cat = bob

Answer

var sample = "/foo/1/bar/2/cat/bob".substring(1);
var finalObj = {};

var arr = sample.split('/');

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

console.log(finalObj);

Comments