4

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

5
  • 2
    There's no such thing as "JSON object". You will most likely want just "object". Commented Jun 5, 2012 at 15:42
  • 1
    added clarification thank you, Oleg. Commented Jun 5, 2012 at 15:47
  • Well, it doesn't seems to be that hard to split it by [] blocks and auto-vivify objects on demand. The only tricky part would be is to vivify Array object for levels where only numeric indices are used. Commented Jun 5, 2012 at 16:04
  • @OlegV.Volkov, that's what is the problem! it doesn't seem to be that hard, but try solving it, it will surely eat your brain up. I am trying to solve it since last 15+ minutes, not even close to the solution! Commented Jun 5, 2012 at 16:07
  • to break things up I am doing this: strAry = myArray[i].replace(/\]/g, "").split("["); But that is only part of the puzzle. Commented Jun 5, 2012 at 16:11

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

sweet! short and really nice!
MMmm, some new things I haven't seen before thanks. The solution I had wasn't nearly as elegant as this. Gold Stars for you, Shedal.
This does not create Arrays for numerical indizes, as it should. I think you can easily fix that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.