我在变量中有一个json结构,说“data”就像这样
{
"SearchWithMasterDataDIdAndScandefinitionDAO": [
{
"dateDm_id": 20120602,
"issueValue": "ELTDIWKZ",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
},
{
"dateDm_id": 20120602,
"issueValue": "LTDFPVOI",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
},
{
"dateDm_id": 20121005,
"issueValue": "LTDILWGY",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
},
{
"dateDm_id": 20121005,
"issueValue": "YMORCLTD",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
}
]
}
现在我想将此结构更改为这样的结构 其中每个对象的datedm_id成为新json结构的根,其中数组为值 新的通缉结构:
{
"20120602": [
{
"issueValue": "ELTDIWKZ",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
},
{
"issueValue": "LTDFPVOI",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
}
],
"20121005": [
{
"issueValue": "YMORCLTD",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 1
},
{
"issueValue": "COOPER",
"scanName": "Company Stored as Person (Given Name)",
"severityCode": 1,
"severityName": "High",
"totalDiscovered": 15
}
]
}
请帮我解决这个问题
答案 0 :(得分:1)
请参阅小提琴:http://jsfiddle.net/YVB2Y/
总之,您需要在for循环中创建一个对象。
var returnVar = {}
b.SearchWithMasterDataDIdAndScandefinitionDAO.forEach(function(item){
var thisItem;
if(returnVar[item.dateDm_id] == undefined){
thisItem = [];
returnVar[item.dateDm_id] = thisItem;
}
else {
thisItem = returnVar[item.dateDm_id];
}
var obj = {};
obj.issueValue = item.issueValue;
//and so on..
thisItem.push(obj);
});
console.log(returnVar);
答案 1 :(得分:0)
underscore.js非常适合处理复杂的数据结构:
var json = { ... };
var result = _.groupBy(json['SearchWithMasterDataDIdAndScandefinitionDAO'],
function (iterator) {
var key = iterator['dateDm_id'];
delete iterator['dateDm_id'];
return key;
});
console.log(result);