如何使用' /'组成的键/值字符串创建对象/数组

时间:2016-12-01 15:02:19

标签: javascript jquery

请使用以下字符串:

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

我需要将其解析为最终为的对象或数组:

foo = 1
bar = 2
cat = bob

4 个答案:

答案 0 :(得分:5)



        if 'users input' in (command = to left):
            Left_new = input("How many places would you like to move left")))

        elif 'users input' in (command = right):
            Right_new = input("How many places would you like to move right")))

        elif 'users input' in (= to up):
           up_new = input("How many places would you like to move up")))

        elif 'users input' in (= down ):
            Down_new =input("How many places would you like to move down")))

        else:
            if  ( users input <9) or ( users input > 100 ):
                print("Sorry one of your inputs were invalid...")
&#13;
&#13;
&#13;

答案 1 :(得分:2)

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

正则表达式是各种解析的首选工具:

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

答案 3 :(得分:0)

只为了它的乐趣,

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