我想根据原始json数据和预期的json数据重构json。
如果仔细查看原始json数据,则我所在的国家/地区不属于Male / Female属性。我希望基于国家(地区)模块内的方向属性将国家(地区)模块置于“男性/女性”属性内。因此在后数据中,我将在“男性”属性中有1个国家模块(因为有1个男性记录),而在“女性”属性中有2个国家模块(因为有2个女性记录)。
原始json数据如下:
{
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
]
}
预期的json数据:
{
"Implementations": [
{
"Male": {
"Gender": "Male"
"Country": [
{
"Orientation": "Male",
"Name": ABCD
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female"
"Country": [
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
]
}
程序:
var Implementations = {
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
]
}
var output = [];
for (k in Implementations.Implementations.Male) {
var temp = [];
for (j in Implementations.Implementations.Male[k]) {
temp.push({
Country: j
});
}
output.push({
"Implementations": k,
Country: temp
});
}
console.log(output);
提前谢谢!
答案 0 :(得分:1)
您的程序无法运行,因为Implementations.Implementations
是一个数组,它没有名为Male
的字段。
这是一个工作代码段:
//Original JSON data in question.
var Implementations = {
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
]
}
// Program that make the conversion
var finalResult = [];
for (var i=0; i<Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j=0; j<currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
console.log(JSON.stringify(finalResult));