Javascript accessing name/value pairs

resopollution picture resopollution · Dec 17, 2009 · Viewed 10.1k times · Source

I'm getting JSON name/value pairs that looks like this:

{
   "Name":"parentid",
   "Value":"blah"
},
{
   "Name":"siteid",
   "Value":"blah"
},
{
   "Name":"sitename",
   "Value":"blah"
}

But I would like to access the "name" value as the KEY, and the "value" value as the VALUE. Is there an elegant way to turn that piece of JSON into something like this?

{'parentid', 'blah'},
{'sitename', 'blah'}

Answer

albertein picture albertein · Dec 17, 2009

Try this:

var items = [
    {
       "Name":"parentid",
       "Value":"blah"
    },
    {
       "Name":"siteid",
       "Value":"blah"
    },
    {
       "Name":"sitename",
       "Value":"blah"
    }
];

var results = new Object();

for (var i = 0; i < items.length; i++)
{
    results[items[i].Name] = items[i].Value;
}

This will result in something like:

var results = { parentid: "Blah", siteid: "Blah", sitename: "Blah" };