[英]Create Multiple dictionary from single single JSON response in javascript?
假设我有一个来自服务器的 JSON 响应,其结构如下
var data={
"Data1": {
"height": 39,
"weight": 62,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5,
"color_srv": "#ffff00"
},
"Data2": {
"height": 0,
"weight": 40,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5,
"color_srv": "#ff0000"
}
}
我希望这个数据字典在保持结构的同时将某些数据分成两个字典。 例如
var data_height = {
"Data1":{
"height": 39,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5,
},
"Data2":{
"height": 0,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5,
}
}
var data_weight = {
"Data1":{
"weight": 39,
"shape": {
"length": 19,
"width": 72
},
"color_srv": "#00ff00",
"radius": 9.5,
},
"Data2":{
"weight": 0,
"shape": {
"length": 19,
"width": 72
},
"color_srv": "#000000",
"radius": 2.5,
}
}
上述两个字典用于不同的目的,因此在获得统一结果后,我想如何将后端的单个数据拆分为两个不同的字典。
这是我尝试做的事情,但它会引发错误
解决方案1:
var serve={},live={};
for(d in data){
pname = d.split(':')[0];
serve['pname'].radius= data[d].radius;
serve['pname'].center= data[d].center;
serve['pname'].color= data[d].color_srv;
live['pname'].radius= data[d].radius;
live['pname'].center= data[d].center;
live['pname'].color= data[d].color;
serve['pname'].numbers= data[d].serving;
live['pname'].numbers= data[d].living;
serve['pname'].place= pname;
live['pname'].place= pname;
}
解决方案2:
var serve={},live={};
for(d in data){
pname = d.split(':')[0];
serve['radius']= data[d].radius;
serve['center']= data[d].center;
serve['color']= data[d].color_srv;
live['radius']= data[d].radius;
live['center']= data[d].center;
live['color']= data[d].color;
serve['numbers']= data[d].serving;
live['numbers']= data[d].living;
serve['place']= pname;
live['plcae']= pname;
}
上述两种解决方案似乎都不起作用。
正如 Nina 所说,只需克隆对象并从每个对象中删除不需要的属性。 在这里,我将reduce
与具有data_height
和data_height
属性的初始对象一起使用。
var clone = function (obj) { return JSON.parse(JSON.stringify(obj)); }
var output = Object.keys(data).reduce(function (p, c) {
var obj = data[c];
p.data_height[c] = clone(obj);
delete p.data_height[c].weight;
delete p.data_height[c].color_srv;
p.data_weight[c] = clone(obj);
delete p.data_weight[c].height;
delete p.data_weight[c].color;
return p;
}, { data_height: {}, data_weight: {} });
输出
{
"data_height": {
"Data1": {
"height": 39,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5
},
"Data2": {
"height": 0,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5
}
},
"data_weight": {
"Data1": {
"weight": 62,
"shape": {
"length": 19,
"width": 72
},
"radius": 9.5,
"color_srv": "#ffff00"
},
"Data2": {
"weight": 40,
"shape": {
"length": 19,
"width": 72
},
"radius": 2.5,
"color_srv": "#ff0000"
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.