首页 > 解决方案 > 如何获取所需的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",
              "currency": "USD"
            },
            {
              "amount": "250",
              "currency": "IND"
            }
          ],
          "loyal": "250"
        }
      ]
    },
    {
      "invetmentId": "111",
      "name": "USA tech",
      "performance": [
        {
          "id": "245",
          "performanceSet": [
            {
              "amount": "956",
              "currency": "ASD"
            },
            {
              "amount": "231",
              "currency": "USD"
            },
            {
              "amount": "233",
              "currency": "USD"
            },
            {
              "amount": "250",
              "currency": "IND"
            }
          ],
          "loyal": "250"
        }
      ]
    }
  ]
}
]
}

所以我需要的是我需要性能.id = 123 的投资名称,即它应该返回“印度科技”。所以我想知道这是否可能,如果是的话,我怎么能得到它?

标签: jsonjsonpath

解决方案


此方法不使用嵌套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", currency: "USD", }, { amount: "250", currency: "IND", }, ], loyal: "250", }, ], }, { invetmentId: "111", name: "USA tech", performance: [ { id: "245", performanceSet: [ { amount: "956", currency: "ASD", }, { amount: "231", currency: "USD", }, { amount: "233", currency: "USD", }, { amount: "250", currency: "IND", }, ], loyal: "250", }, ], }, ], }, ], };
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));


推荐阅读