简体   繁体   English

JSON的Assoc数组到变量?

[英]JSON Assoc Array to Variables?

I have a JSON associate array 我有一个JSON关联数组

[{"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. 我在查看Object.keys但是找不到合适的解决方案。

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/ http://jsfiddle.net/FNAtw/

This will give you an array stored in newArray with two elements. 这将为您提供一个存储在newArray的数组,其中包含两个元素。 The first element is an object with kvps theatre: 'Test' and time: '5:00pm' . 第一个元素是对象,其kvps theatre: 'Test'time: '5:00pm' The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm' . 第二个元素是一个对象,其对象具有kvps theatre: 'Testing2' Testing2 theatre: 'Testing2'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. 如果JSON总是和上面一样简单,则应该可以使用。 But it's brittle... 但这很脆...

If you have a JS object, you could use Object.keys . 如果您有JS对象,则可以使用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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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