简体   繁体   中英

JSON Assoc Array to Variables?

I have a JSON associate array

[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]

and I want to make it so that it becomes an array where

{
  theatre = Test
  time = 5:00pm
},
{
  theatre = Testing2
  time = 4:30 pm
}

But I can't figure out how to take a key name and make it a value...

Any help? I was looking at Object.keys but I couldn't find a suitable solution.

You have an array with object values. You'd need to loop over them:

var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
var newArray = [];

for (var i = 0; i < oldArray.length; i++) {
    var keys = Object.keys(oldArray[i]);

    newArray.push({
        theatre: keys[0],
        time: oldArray[i][keys[0]]
    });
}

http://jsfiddle.net/FNAtw/

This will give you an array stored in newArray with two elements. The first element is an object with kvps theatre: 'Test' and time: '5:00pm' . The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm' .

Try this workaround:

var json = '[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]';
var betterJson = json.replace('{"', '{"theatre":"').replace('":"','",time:"');

If the JSON is always as simple as above, then this should work. But it's brittle...

If you have a JS object, you could use Object.keys . That will work in the latest browsers.

You can also loop each item and just save the 1st item.

var result = [];
var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
for (var i = 0; i < str.length; i++) {
    var obj = {};
    foreach (var key in str[i]) {
        obj.theatre = key;
        obj.time = str[i][key];
    }
    result.push(obj);
}

May be a bit clunky, BUT should work cross-browser.

var js = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
var newJSON = []
for(var i = 0; i< js.length; i++) {
    for( var key in js[i]) {
        if(js[i].hasOwnProperty(key)) {
            var tmpJS= {};
            tmpJS['theater'] =  key;
            tmpJS['time'] = js[i][key];
            newJSON.push(tmpJS);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM