2

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

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Correct for question asked.
2

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)

5 Comments

Very elegant, @synthet1c.
what happend to the initial / in the string ??
Perfect. I decided to trim the initial / on the string to make this work.
Is there a reason for using ii as an indexer or is that just something you prefer over the conventional i?
easier to search for with ctrl + f you will probably have at least one i in your code, but ii is pretty much never used.
1

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

2 Comments

That's great but quite unreadable imho and i guess not that optimized. BUT that's just my opinion and you got my vote
I’d use ([^\/]*) instead of (\w+). Empty key names and values are allowed and aren’t restricted to alphanumeric characters.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.