uma
uma

Reputation: 1577

need to filter and first matching element of obect array in typescript?

I have objected array , came through the rest call , and the data structure looks like below. I need to filter that and get the first matching object. I used a typescript filter and try to find as well but did not return the first matching object. need some expert help to resolve this

"products": [
                    {
                        "subProduct": {
                            "Id": "14",          
                            "Type": "Main",
                          
                        }
                      
                    },
                    {
                        "subProduct": {
                            "Id": "2",
                            "Type": "B",
                        }
                    },
                    {
                        "subProduct": {
                            "Id": "2",
                            "Type": "B",
                        }
                    },
                    {
                        "subProduct": {
                            "Id": "22",
                            "Type": "Main",
                        }
                    }
             
                ]

code :

const mainProduct = products.find(product => {
 product.subProduct.Type === Type.Main;
 })

Upvotes: 0

Views: 1299

Answers (1)

TinDora
TinDora

Reputation: 390

You missed the return inside the find().

Must be:

const mainProduct = products.find(product => {
 return product.subProduct.Type === Type.Main;
})

Or without the return:

products.find(product => product.subProduct.Type === Type.Main)

Upvotes: 1

Related Questions