我有一个要求,需要根据特定键从 JSON 对象中提取元素/属性。我在这里非常困惑如何获取。
{ "metadata":{
"lastSyncTime":"2000-11-21T16:07:53",
"dataFromDB":true
},
"allocationReports":[ {
"allocatedUserCount":100,
"healthGoalName":"Eat Healthier",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 2},
{segmentValue: "30-39", allocatedUserCount: 13},
{segmentValue: "20-29", allocatedUserCount: 23}
]
},
{
"allocatedUserCount":130,
"healthGoalName":"Feel Happier",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 20},
{segmentValue: "30-39", allocatedUserCount: 3},
{segmentValue: "20-29", allocatedUserCount: 53}
]
},
{
"allocatedUserCount":150,
"healthGoalName":"Quit Smoking",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 19},
{segmentValue: "30-39", allocatedUserCount: 1},
{segmentValue: "20-29", allocatedUserCount: 22},
{segmentValue: "10-19", allocatedUserCount: 47}
]
}
],
"overall":{
"usersWithGoalCount":0,
"registeredCount":500,
"eligibleCount":280
}
}
我们如何根据healthgoalName提取segment数组。例如,我编写了一个以“healthGoalName”(假设戒烟)作为参数的方法。 这个方法应该返回 -
"segments": [
{segmentValue: "40-49", allocatedUserCount: 19},
{segmentValue: "30-39", allocatedUserCount: 1},
{segmentValue: "20-29", allocatedUserCount: 22},
{segmentValue: "10-19", allocatedUserCount: 47}
]
提前致谢。
最佳答案
我假设问题中的 JSON 显示名为 obj
的对象的内容,该对象在名为 getSegments
的方法的上下文中可用。如果情况并非如此,您需要将该对象作为第二个参数提供给该方法。
function getSegments(healthGoalName)
{
const allocationReport = obj.allocationReports.find(allocationReport => allocationReport.healthGoalName === healthGoalName);
return allocationReport ? allocationReport.segments : null;
}
function getSegments(healthGoalName)
{
const allocationReport = obj.allocationReports.find(allocationReport => allocationReport.healthGoalName === healthGoalName);
return allocationReport ? allocationReport.segments : null;
}
const obj =
{
"metadata":{
"lastSyncTime":"2000-11-21T16:07:53",
"dataFromDB":true
},
"allocationReports":[ {
"allocatedUserCount":100,
"healthGoalName":"Eat Healthier",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 2},
{segmentValue: "30-39", allocatedUserCount: 13},
{segmentValue: "20-29", allocatedUserCount: 23}
]
},
{
"allocatedUserCount":130,
"healthGoalName":"Feel Happier",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 20},
{segmentValue: "30-39", allocatedUserCount: 3},
{segmentValue: "20-29", allocatedUserCount: 53}
]
},
{
"allocatedUserCount":150,
"healthGoalName":"Quit Smoking",
"segments": [
{segmentValue: "40-49", allocatedUserCount: 19},
{segmentValue: "30-39", allocatedUserCount: 1},
{segmentValue: "20-29", allocatedUserCount: 22},
{segmentValue: "10-19", allocatedUserCount: 47}
]
}
],
"overall":{
"usersWithGoalCount":0,
"registeredCount":500,
"eligibleCount":280
}
};
const segments = getSegments("Quit Smoking");
console.log({ segments });
关于javascript - 如何根据 typescript 中的键从对象中提取特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62920219/