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)
/ in the string ??ii as an indexer or is that just something you prefer over the conventional i?ctrl + f you will probably have at least one i in your code, but ii is pretty much never used.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);
([^\/]*) instead of (\w+). Empty key names and values are allowed and aren’t restricted to alphanumeric characters.