skip to Main Content

I have the following nested object:

const sites = [
 {
  "name": "name1",
  "list": [
     {
       "id":1,
       "name": "Year",
       "type": "int"
     }
  ]
 }
]

I would like to check if one item is present in the object by checking the id:

const item1 = {
       "id":1,
       "name": "Year",
       "type": "int"
     }
const item2 = {
       "id":2,
       "name": "Month",
       "type": "int"
     }

So I do:

sites.some(i => i.list.some(j => j.id === item1.id)) //True

sites.some(i => i.list.some(j => j.id === item2.id)) //False

Is there a better way to do this query without using so many .some?

2

Answers


  1. Your .some approach is perfectly reasonable. Use functions to keep DRY.

    function isItemPresent(sites, item) {
      return sites.some(site => site.list.some(subItem => subItem.id === item.id));
    }
    
    const item1 = {
      "id": 1,
      "name": "Year",
      "type": "int"
    };
    
    const item2 = {
      "id": 2,
      "name": "Month",
      "type": "int"
    };
    
    console.log(isItemPresent(sites, item1)); // true
    console.log(isItemPresent(sites, item2)); // false
    

    If you want to use Lodash, it can make it a little more negligibly short.

    function isItemPresent(sites, item) {
      return _.some(sites, site => _.some(site.list, { id: item.id }));
    }
    
    Login or Signup to reply.
  2. 2 some()‘s are the fastest way for 2 checks. So it’s totally ok.
    If you have many items in the lists and check many items I would suggest gather IDs in a Set, then the checking is trivial:

    const set = new Set(sites.flatMap(i => i.list.map(j => j.id)));
    
    console.log(set.has(item1.id));
    console.log(set.has(item2.id));
    <script>
    
    const item1 = {
           "id":1,
           "name": "Year",
           "type": "int"
         }
    const item2 = {
           "id":2,
           "name": "Month",
           "type": "int"
         }
    const sites = [
     {
      "name": "name1",
      "list": [
         {
           "id":1,
           "name": "Year",
           "type": "int"
         }
      ]
     }
    ];
         
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search