Search code examples
javascriptarraysjavascript-objects

Search in array of objects that sits in object in array


I need to check if bidder "one" already has "placementId": "4" in arr. I've tried to combine for loop with filter with no luck. Is there any elegant way to solve this?

var check = { "one": "4" },
    arr = [{
        "code": "qwe",
        "bids": [{
                "bidder": "one",
                "params": {
                    "placementId": "1"
                }
            },
            {
                "bidder": "two",
                "params": {
                    "placementId": "2"
                }
            }
        ]
    }, {
        "code": "asd",
        "bids": [{
            "bidder": "one",
            "params": {
                "placementId": "3"
            }
        }]
    }];

Solution

  • I think find() is the way to go here. You want to find an element in your array where one of the bids has a bid.bidder of "one" and bid.params.placementId of 4. Or undefined if it doesn't exist.

    This can be expressed in javascript with something like:

    let found = arr.find(code => 
                code.bids.some(bid => bid.bidder === "one" && bid.params.placementId === "4"))
    

    Since you only want to know whether it exists or not you basically only care if it returns something or undefined. Here's a positive and negative example:

    var check = { "one": "1" },arr = [{"code": "qwe","bids": [{"bidder": "one","params": {"placementId": "1"}},{"bidder": "two","params": {"placementId": "2"}}]}, {"code": "asd","bids": [{"bidder": "one","params": {"placementId": "3"}}]}];
    
    // user one placement id 4 does not exist
    let found = arr.find(code => code.bids.some(bid => bid.bidder === "one" && bid.params.placementId === "4"))
    console.log(found !==  undefined)
    
    // user two placement id 2 does exist
    found = arr.find(code => code.bids.some(bid => bid.bidder === "two" && bid.params.placementId === "2"))
    console.log(found !==  undefined)