根据特定性别数据拆分组合列表用于 ID
Split a combined List based on particular gender data is present for ID
这是一个组合列表,具有唯一的 ageCode。
[
{
"ageCode": 1,
"ageDesc": "0-4",
"qM": 358,
"sM": 158,
"qF": 328,
"sF": 258
},
{
"ageCode": 3,
"ageDesc": "15-59",
"qM": 525,
"sM": 125
},
{
"ageCode": 4,
"ageDesc": "60+",
"qF": 458,
"sF": 358
}
]
需要根据年龄代码的 M 和 F 值是否存在,将组合列表拆分为单独的对象。转换后的列表如下所示。如果没有 "M" 日期,则不会有 "gender" 的对象:"M" 同样适用于 "F"
[
{
"ageCode": 1,
"ageDesc": "0-4",
"q": 358,
"s": 158,
"gender": "M"
},
{
"ageCode": 1,
"ageDesc": "0-4",
"q": 328,
"s": 258,
"gender": "F"
},
{
"ageCode": 3,
"ageDesc": "15-59",
"q": 525,
"s": 125,
"gender": "M"
},
{
"agCode": 4,
"ageDesc": "60+",
"q": 458,
"s": 358,
"gender": "F"
}
]
尝试过的解决方案:
for(let item of this.ageData) {
if (this.ageData.find((i) => { i.agCode=== item.agCode})){
//}
}
这里需要重复和多次for循环等问题,有什么有效的方法可以实现吗
尝试下一个代码
const combined = [
{
"ageCode": 1,
"ageDesc": "0-4",
"qM": 358,
"sM": 158,
"qF": 328,
"sF": 258
},
{
"ageCode": 3,
"ageDesc": "15-59",
"qM": 525,
"sM": 125
},
{
"ageCode": 4,
"ageDesc": "60+",
"qF": 458,
"sF": 358
}
];
const original = combined.reduce((result, item) => {
if (item.qM !== undefined) {
result.push({
"ageCode": item.ageCode,
"ageDesc": item.ageDesc,
"q": item.qM,
"s": item.sM,
"gender": "M"
});
}
if (item.qF !== undefined) {
result.push({
"ageCode": item.ageCode,
"ageDesc": item.ageDesc,
"q": item.qF,
"s": item.sF,
"gender": "F"
});
}
return result;
}, []);
console.log(original);
这是一个组合列表,具有唯一的 ageCode。
[
{
"ageCode": 1,
"ageDesc": "0-4",
"qM": 358,
"sM": 158,
"qF": 328,
"sF": 258
},
{
"ageCode": 3,
"ageDesc": "15-59",
"qM": 525,
"sM": 125
},
{
"ageCode": 4,
"ageDesc": "60+",
"qF": 458,
"sF": 358
}
]
需要根据年龄代码的 M 和 F 值是否存在,将组合列表拆分为单独的对象。转换后的列表如下所示。如果没有 "M" 日期,则不会有 "gender" 的对象:"M" 同样适用于 "F"
[
{
"ageCode": 1,
"ageDesc": "0-4",
"q": 358,
"s": 158,
"gender": "M"
},
{
"ageCode": 1,
"ageDesc": "0-4",
"q": 328,
"s": 258,
"gender": "F"
},
{
"ageCode": 3,
"ageDesc": "15-59",
"q": 525,
"s": 125,
"gender": "M"
},
{
"agCode": 4,
"ageDesc": "60+",
"q": 458,
"s": 358,
"gender": "F"
}
]
尝试过的解决方案:
for(let item of this.ageData) {
if (this.ageData.find((i) => { i.agCode=== item.agCode})){
//}
}
这里需要重复和多次for循环等问题,有什么有效的方法可以实现吗
尝试下一个代码
const combined = [
{
"ageCode": 1,
"ageDesc": "0-4",
"qM": 358,
"sM": 158,
"qF": 328,
"sF": 258
},
{
"ageCode": 3,
"ageDesc": "15-59",
"qM": 525,
"sM": 125
},
{
"ageCode": 4,
"ageDesc": "60+",
"qF": 458,
"sF": 358
}
];
const original = combined.reduce((result, item) => {
if (item.qM !== undefined) {
result.push({
"ageCode": item.ageCode,
"ageDesc": item.ageDesc,
"q": item.qM,
"s": item.sM,
"gender": "M"
});
}
if (item.qF !== undefined) {
result.push({
"ageCode": item.ageCode,
"ageDesc": item.ageDesc,
"q": item.qF,
"s": item.sF,
"gender": "F"
});
}
return result;
}, []);
console.log(original);