gpt4 book ai didi

javascript - 从包含多维的字符串构建 JSON 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:20:26 25 4
gpt4 key购买 nike

我有一个名称/值对象数组(如下)。名称经过格式化以表示多维数组。

我需要从中构建一个完整的 JavaScript 对象(底部)。

[{
name: "getQuote[origin]",
value: "Omaha,NE"
},
{
name: "getQuote[destination]",
value: "10005"
},
{
name: "getQuote[country]",
value: "us"
},
{
name: "getQuote[vehicles][0][year]",
value: "1989"
},
{
name: "getQuote[vehicles][0][make]",
value: "Daihatsu"
},
{
name: "getQuote[vehicles][0][model]",
value: "Charade"
},
{
name: "getQuote[vehicles][0][count]",
value: "1"
}]

像这样:

{getQuote : 
{ origin : Omaha},
{ destination : 10005},
{vehicles : [
{
year : 1989,
make: Honda,
model : accord
},
{
//etc
}]

n

最佳答案

你可以手动完成,像这样:

var source = [ /* Your source array here */ ];
var dest = {};

for(var i = 0; i < source.length; i++)
{
var value = source[i].value;

var path = source[i].name.split(/[\[\]]+/);

var curItem = dest;

for(var j = 0; j < path.length - 2; j++)
{
if(!(path[j] in curItem))
{
curItem[path[j]] = {};
}

curItem = curItem[path[j]];
}

curItem[path[j]] = value;
}

dest 是结果对象。

检查它在这里工作:http://jsfiddle.net/pnkDk/7/

关于javascript - 从包含多维的字符串构建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900283/

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