gpt4 book ai didi

javascript - 正确解析url字符串

转载 作者:行者123 更新时间:2023-12-03 10:36:28 25 4
gpt4 key购买 nike

无法按照我想要的方式解析 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());
});

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

最佳答案

在 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

关于javascript - 正确解析url字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28967841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com