4

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

我需要用它构建一个完整的 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

4

1 回答 1

2

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

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/

于 2012-06-05T16:17:01.080 回答