正确解析 url 字符串

parsing url string correctly

在按照我的意愿解析 url 对象时遇到问题,url 字符串还是个新手希望得到一些帮助。我的对象看起来像这样:

{mod1: "/hello/world", mod25: "/hey/jude/how/are/you"}

我需要将它解析成这样的东西

{
"mod1" : {"hello" : ["world"]},
"mod2" : {"hey" : ["jude","how","are","you"]}
}

如何将此 url 解析为这样的对象? 谢谢!

编辑:到目前为止

  var parseObj = $location.search();

            _.each(parseObj, function(ob){
                console.log(ob.split());
            });

这给了我字符串,但是我不确定现在如何将它们拆分成一个对象,其中键是第一项

遍历对象属性,拆分值并将它们插入第二个对象。

function parse(obj) {
  var out = {},
    parts;
  for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      out[prop] = {};
      // replace the first forward slash with nothing so the first 
      // element of the array is not an empty string.
      parts = obj[prop].replace('/', '').split('/');
      // make the first element of the array the key and assign the 
      // rest of the array as the value.
      out[prop][parts.shift()] = parts;
    }
  }
  return out;
}

var obj = parse({
  mod1: "/hello/world",
  mod25: "/hey/jude/how/are/you"
});
// just display the object
document.write('<pre>' + JSON.stringify(obj, 0, 3));

这个怎么样?

var x = {mod1: "/hello/world", mod25: "/hey/jude/how/are/you"};

var result = {};

for(var i in x) {
  var entries = x[i].split('/');
  var firstEntry = entries[1];
  var arr = [];
  for(var j = 2; j < entries.length; j++) {
    arr.push(entries[j]);
  }
  var obj = {}
  obj[firstEntry] = arr;
  result[i] = obj;
}

console.log(result);

在 vanilla JS 中为您提供的简单注释步骤:

// pass in the object to the function
function organise(obj) {

    // create a new object which we will return from the function
    var obj2 = {};

    // loop over the object we passed in
    for (var p in obj) {

        // create a temporary object
        var tmp = {};

        // split the value of current key/value pair into an array
        var arr = obj[p].split('/');

        // set the key of the temporary object to the second element
        // (because the first element of the array is an empty string)
        var key = arr[1];

        // add the rest of the array as the value of the new key
        // of the temporary object
        tmp[key] = arr.slice(2);

        // finally add the new temporary object as the value of the key
        // of the object we want to return
        obj2[p] = tmp;
    }

    // return the object from the function
    return obj2;
}

organise(obj);

DEMO