Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript accessing name/value pairs

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'}
like image 975
resopollution Avatar asked Oct 29 '25 08:10

resopollution


1 Answers

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" };
like image 139
albertein Avatar answered Oct 31 '25 22:10

albertein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!