如何获取所需的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));