如何解决如何获取所需的json路径?
我具有这种JSON结构,并且我希望在对层次结构中较低元素施加条件时获取层次结构中的较高元素
{
"name": "ninja","contry": "India","Account": [
{
"id": "123","orgId": 223,"investment": [
{
"invetmentId": "111","name": "India tech","performance": [
{
"id": "123","performanceSet": [
{
"amount": "210","currency": "YEN"
},{
"amount": "231","currency": "USD"
},{
"amount": "233",{
"amount": "250","currency": "IND"
}
],"loyal": "250"
}
]
},{
"invetmentId": "111","name": "USA tech","performance": [
{
"id": "245","performanceSet": [
{
"amount": "956","currency": "ASD"
},"loyal": "250"
}
]
}
]
}
]
}
所以我需要的是需要有Performance.id = 123的投资名称,即它应该返回“ India tech”。所以我想知道是否有可能,如何获得?
解决方法
此方法不使用嵌套的forEach
,即O(n²),一旦找到匹配的结果,它将停止迭代
data = { name: "ninja",contry: "India",Account: [ { id: "123",orgId: 223,investment: [ { invetmentId: "111",name: "India tech",performance: [ { id: "123",performanceSet: [ { amount: "210",currency: "YEN",},{ amount: "231",currency: "USD",{ amount: "233",{ amount: "250",currency: "IND",],loyal: "250",{ invetmentId: "111",name: "USA tech",performance: [ { id: "245",performanceSet: [ { amount: "956",currency: "ASD",};
res = [];
finfperf = (id) => {
data.Account.forEach((inv) =>
res.push(
inv.investment.find((o) => o.performance.some((a) => a.id == id)).name
)
);
return res;
};
console.log(finfperf(123));
console.log(finfperf(245));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。