Dean Peterson
Dean Peterson

Reputation: 261

Build JSON Object from string containing multi-dimensional

I have an array of name/value objects (below). The names are formatted to represent multi-dimensional array.

I need to build a full JavaScript object out of it(bottom).

[{
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"
}]

Into something like this:

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

n

Upvotes: 4

Views: 902

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34601

You can do it manually, like this:

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 is the resulting object.

Check it working here: http://jsfiddle.net/pnkDk/7/

Upvotes: 2

Related Questions