0

I'm stuck since a while trying to access a nested array inside another array after filtering it by an id. To be clear, this is the mock data I have:

  bundleSets: [
            {
                id: 1,
                title: "bundle set 1",
                bundles: [
                    {
                        bundleTitle: "bundle 1",
                        content:[]
                    },
                    {
                        bundleTitle: "bundle 2",
                        content:[]
                    }
                ]
            },
            {   id:2,
                title: "bundle set 2",
                bundles: [
                    {bundleTitle: "ciaopao", content:[]}
                ]
            },
            {   id:3,
                title: "bundle set 3",
                bundles: [
                    {bundleTitle: "ciapo", content:[]}
                ]
            }
        ]

Now I need to filter each bundleSets by id, and then access the bundles array inside and mapping those elements. This is what I tried to do:

 const [key,setKey]=useState(1)
  const [bundles,setBundles]=useState([])
  
  
   


  useEffect(()=>{

    const filteredBundles = bundleSets && bundleSets.filter(bundleSet=>bundleSet.id==key).map(filteredBundles=>{
      return filteredBundles.bundles
    })

  setBundles(filteredBundles)

   

  },[key])

Now If I try mapping the new state I can see on the console.log a weird [Array(1)] instead of the usual [{}] and I can't render it to the page. Where am I getting wrong with this?

0

1 Answer 1

1

Array.prototype.map returns an array and the callback you're passing to the map method returns filteredBundles.bundles which is an array. So, you get an array of arrays. filteredBundles is a confusing name, btw.

Since you're looking up the bundle by id and the ids are unique in the bundleSets array, you can use Array.prototype.find to find the bundle set by id and then get the bundle array. You can return an empty array if find returns undefined (if the key is not found).

const bundles = bundleSets?.find(set => set.id === key)?.bundles || []
Sign up to request clarification or add additional context in comments.

Comments

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.