David David - 1 year ago 68
Javascript Question

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

Take the following string:


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

foo = 1
bar = 2
cat = bob

Answer Source

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];


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download