Thursday, December 17, 2009

JS Array to object

So I wanted to be able to use an object in JSON but transfer it as an array.

The issue is that the syntax of el.name is nice, but the {name:"joe"} is longer then just ["joe"].

The way around it is very simple actually.

We'll start with a normal object
{
firstname: "Joe",
lastname: "Shmoe",
address: "123 Twiddledeedoo Lane",
}

Now we do this in javacript:

var keys = ["firstname", "lastname", "address"], obj = {};

And we transfer ["Joe","Shmoe","123 Twiddledeedoo Lane"] as the payload.

Now the code is fairly straight forward. Assuming:

var values = ["Joe","Shmoe","123 Twiddledeedoo Lane"];

To efficiently get back to the object we do the following:

do{
obj[keys.pop()] = values.pop();
} while (keys.length);

And that's it. It's so straight forward ... I don't know why it was a mystery for so long...

No comments:

Post a Comment

Followers