[英]Change representation of JSON object to explicit key/value format
I have the following JSON: 我有以下JSON:
{
"temperature": "22.2",
"power": "6",
"current": "156"
}
and I need to convert it to this explicit structure: 我需要将其转换为以下显式结构:
{
"key": "temperature",
"value": "22.2"
},
{
"key": "power",
"value": "6"
},
{
"key": "current",
"value": "156"
}
Is there an elegant, simple and quick way to do this? 有没有一种优雅,简单,快捷的方法来做到这一点?
Best, thx 最好,谢谢
var newStructure = Object.keys(obj).map(function(key){
return {'key':key, 'value':obj[key]}
})
Example 例
var obj = { "temperature": "22.2", "power": "6", "current": "156" } var arr = Object.keys(obj).map(function(key){return {'key':key,'value':obj[key]}}) console.log(arr)
Object.hashToKeyValuePairs = function (hash) { var ret = []; for (var i in hash) ret.push({ key: i, value: hash[i]}); return ret; }; // example document.body.innerHTML = JSON.stringify( Object.hashToKeyValuePairs({ a: 1, b: 2, c: 3 }) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.