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

我有一个名称/值对象数组(如下).名称被格式化为表示多维数组.

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

ñ

最佳答案 您可以手动执行此操作,如下所示:

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/

点赞