Search code examples
javascriptreactjsjslint

How to search nested object by following JSLint


I have my object structured as below and I want to find the product with provided ID.

0 :{
   id: 0,
   title: 'xxxx',
   url: "www.test.com"
   quantity: 100
},
1 :{
   id: 10,
   title: 'xxxx',
   url: "www.test.com"
   quantity: 100
},
// and so on...

In order to search nested attribute within the object, I have written the below function:

export const selectProductById = (state, productId) => {
   const obj_index = Object.keys(state.products).find(function(idx) {
      if (state.products[idx].id == productId) {
         return idx;
      }
   }

   return state.products[obj_index]
}

This works but I will always get a warning during compilation of my react app. Expected '===' and instead saw '=='

But if I change this into === the code will not work anymore, does anyone knows how to change this so that it follows JSLint rules ?


Solution

  • It sounds like the productId is not a number. Cast it to a number first:

    if (state.products[idx].id === Number(productId)) {
    

    But you should return a truthy or falsey value from the .find callback, not something that you're iterating over (since you may not be sure whether it's truthy or falsey, and it's potentially confusing). Return the result of the === comparison instead:

    const { products } = state;
    const obj_index = Object.keys(products).find(
      key => products[key].id === Number(productId)
    );