I'm looking for a vanilla javascript solution to find an object using one or more conditions.
Ideally, I'd like to use a similar syntax as lodash.find and a reusable function that can take one or more conditions:
_.find(products, {code:"BLK")
_.find(products, {code:"BLK", sale: false})
In my case, I'm looking for one object, so I'd prefer find
over filter
.
const products = [
{
title: "Shirt",
color: "Black",
code: "BLK",
sale: true
},
{
title: "Better Shirt",
color: "Black",
code: "BLK",
sale: false
},
{
title: "Blue Shirt",
color: "Blue",
code: "BLU",
sale: false
}
]
// Lodash find using multiple conditions
console.log(_.find(products, {code:"BLK", sale: false}))
// Find all using one condition
console.log(products.filter(product => product.color === 'Black'))
// Find single with multiple conditions
console.log(products.find(product => product.color === 'Black' && product.sale === false ))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
How can I emulate the functionality of _.find from lodash in simple, vanilla js?