gpt4 book ai didi

javascript - JS 数组字符串补丁名称到数组(对象)

转载 作者:行者123 更新时间:2023-12-03 11:58:13 26 4
gpt4 key购买 nike

我在使用 js 数组时遇到问题。我的补丁名称(字符串)看起来像(“user.joey.friends.0.franc”),我需要“压缩”看起来像这样:

console.log( parseArray( "user.joey.friends.0.franc" ) );
//Object {
user: {
joey: {
friends: {
0: {
franc: 1
}
}
}
}
}

有什么想法吗?该怎么做?

最佳答案

这是一种非递归方法,可以帮助您完成大部分工作。

function compress(str) {
var split = str.split('.'), obj = {}, current = obj, i;

for (i = 0; i < split.length; i++){
current[split[i]] = {} ;
current = current[split[i]];
}

return obj;
}

关于javascript - JS 数组字符串补丁名称到数组(对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510551/

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