0

I had this type of JSON structure and I want to fetch the upper element in the hierarchy on applying condition on lower element in hierarchy

 {
  "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"
        }
      ]
    }
  ]
}
]
}

So what I need is I need the investment name for which performance.id = 123 i.e it should return "India tech".So I want to know if that can be possible or not if yes how can I get that?

Ninja
  • 433
  • 3
  • 10
  • There's no `performance.id`. `performance` is an array, so you need to loop over it and check `performance[i].id` – Barmar Aug 20 '20 at 06:00

1 Answers1

2

This method doesn't use nested forEach which is O(n²) and it stops iterating once it finds the matched result

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));
Sven.hig
  • 4,449
  • 2
  • 8
  • 18