1
  for (let material of submission.materials) {
      const { docs } = await getDocs(
        query(collection(db, "materials"), where("name", "==", material.name))
      );
      const materialKpis = docs[0].data().kpis.map((kpi) => {
        return { kpis: kpi.id, value: kpi.value };
      });
      allKpis = [
        ...allKpis,
        {
          material: material.name,
          kpis: materialKpis,
        },
      ];
    }



[{"kpis": [{id: "A4yYU8r9hFxCgEDV77ps", value: 2}], "material": "Test Materiaal"}, 
     {"kpis": [{id: "A4yYU8r9hFxCgEDV77ps", value: 2}, {id: "HhoomonFUYGVv4H4RTj3", value: 3}], 
      "material": "Test Materiaal 2"}
    ]

I have this array of objects called allKpis, containing a nested array of KPI objects with an ID and a value. I want to create a function that would return

   [{"kpis": [{id: "A4yYU8r9hFxCgEDV77ps", value: 2}], "material": "Test Materiaal"}, 
     {"kpis": [{id: "A4yYU8r9hFxCgEDV77ps", value: 2}], 
      "material": "Test Materiaal 2"}
    ]

Since the other KpiId does not exist on all objects. How would i go about doing this?

5
  • can you share how can you convert from the original array to the new array? I can't figure out the logic that you want to implement here. Also, What have you tried so far? Commented Dec 19, 2022 at 10:40
  • should it match both id and value Commented Dec 19, 2022 at 10:40
  • Should only match the the id Commented Dec 19, 2022 at 10:44
  • why is there an inner kpis field {"kpis": [{"kpis": [{id: "A4yYU8r9hFxCgEDV77ps", value: 2}] ` Commented Dec 19, 2022 at 10:48
  • Typo, fixed it now Commented Dec 19, 2022 at 10:50

1 Answer 1

1

You can:

  • Iterate allKpis and count how many occurrences you have of each ID
  • Filter that list of IDs to only keep those that have a count that is equal to the length of allKpis.
  • Turn this list into a Set.
  • Map the objects in allKpis and apply a filter to their kpis arrays, requiring that the id is in that set.

Code to execute after your loop:

const ids = new Set(
    Object.entries(
        allKpis.flatMap(({kpis}) => kpis.map(({id}) => id))
               .reduce((acc, id) => (acc[id] = (acc[id] ?? 0) + 1, acc), {})
    ).filter(([id, count]) => count == allKpis.length)
     .map(([id]) => id)
);
 
allKpis = allKpis.map(o => ({
    ...o,
    kpis: o.kpis.filter(({id}) => ids.has(id))
}));
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick! Now i have to decipher what it does..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.