简体   繁体   中英

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

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

 const str = '/foo/1/bar/2/cat/bob/test/' const parts = str.split('/') .filter(val => val !== '') const obj = {} for (let ii = 0; ii < parts.length; ii+=2) { const key = parts[ii] const value = parts[ii+1] obj[key] = !isNaN(value) ? Number(value) : value } console.log(obj) 

Regular expressions is the tool of choice for all kinds of parsing:

 str = '/foo/1/bar/2/cat/bob' obj = {}; str.replace(/(\\w+)\\/(\\w+)/g, (...m) => obj[m[1]] = m[2]); console.log(obj); 

Just for the fun of it,

let str = "/foo/1/bar/2/cat/bob",
    arr = str.split("/"),
    obj = {};
arr.shift();
while (arr.length) obj[arr.shift()] = arr.shift();

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