我有一些json数据,看起来像:
[{
"key": "Jan",
"value": "400"
}, {
"key": "Apr",
"value": "500"
}, {
"key": "Aug",
"value": "24058.635"
}, {
"key": "Sep",
"value": "2160"
}, {
"key": "Nov",
"value": "115425"
}, {
"key": "Dec",
"value": "32570"
}]
我需要将其转换为类似于
的键值对数组[
[Jan, 400],
[Apr, 500],
[Aug, 24058.635],
[Sep, 2160],
[Nov, 115425],
[Dec, 32570]
]
有人请用Jquery或Javascript代码帮我做这个转换。
答案 0 :(得分:2)
您可以使用map()
函数迭代它们并返回所需的数组。
let json = [{"key":"Jan","value":"400"},{"key":"Apr","value":"500"},{"key":"Aug","value":"24058.635"},{"key":"Sep","value":"2160"},{"key":"Nov","value":"115425"},{"key":"Dec","value":"32570"}];
let obj = json.map(item => [item['key'], item['value']]);
console.log(obj);

答案 1 :(得分:1)
使用 forEach 方法。
var a= [{"key":"Jan","value":"400"},{"key":"Apr","value":"500"},{"key":"Aug","value":"24058.635"},{"key":"Sep","value":"2160"},{"key":"Nov","value":"115425"},{"key":"Dec","value":"32570"}];
var ans=[];
a.forEach(function(a){
ans.push([a["key"],a["value"]]);
})
console.log(ans);

使用地图方法。
var a= [{"key":"Jan","value":"400"},{"key":"Apr","value":"500"},{"key":"Aug","value":"24058.635"},{"key":"Sep","value":"2160"},{"key":"Nov","value":"115425"},{"key":"Dec","value":"32570"}];
var ans=a.map(function(a){
return [a["key"],a["value"]];
})
console.log(ans);

答案 2 :(得分:1)
你可以这样做。
var input = [{
"key": "Jan",
"value": "400"
}, {
"key": "Apr",
"value": "500"
}, {
"key": "Aug",
"value": "24058.635"
}, {
"key": "Sep",
"value": "2160"
}, {
"key": "Nov",
"value": "115425"
}, {
"key": "Dec",
"value": "32570"
}];
var output = input.map(function(obj) {
return [obj.key, obj.value]
});
console.log(output);
答案 3 :(得分:0)
使用数组map()方法:
var jsonObj = [{
"key": "Jan",
"value": "400"
}, {
"key": "Apr",
"value": "500"
}, {
"key": "Aug",
"value": "24058.635"
}, {
"key": "Sep",
"value": "2160"
}, {
"key": "Nov",
"value": "115425"
}, {
"key": "Dec",
"value": "32570"
}];
var newArr = jsonObj.map(function(item) {
return [item['key'],item['value']];
});
console.log(newArr);

使用JavaScript for...in循环:
var jsonObj = [{
"key": "Jan",
"value": "400"
}, {
"key": "Apr",
"value": "500"
}, {
"key": "Aug",
"value": "24058.635"
}, {
"key": "Sep",
"value": "2160"
}, {
"key": "Nov",
"value": "115425"
}, {
"key": "Dec",
"value": "32570"
}];
var newArr = [];
for (var i in jsonObj) {
newArr.push([jsonObj[i].key,jsonObj[i].value]);
}
console.log(newArr);