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

Build JSON Object from string containing multi-dimensional

本文关键字:构建 JSON 对象 字符串 包含多      更新时间:2023-09-26

我有一个名称/值对象数组(如下)。 名称的格式设置为表示多维数组。

我需要从中构建一个完整的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/