Within an array of objects how does one find an object by a certain key name?

I have an an array of Object instances where each object’s own enumerable keys are based on digits only.

[{
  '2': [1, 3],
}, {
  '3': [1, 4],
}, {
  '4': [2, 6],
}]

I need to find the first array item of the first object which owns the digit based key that is provided as the base of my search.

Expected results:

  • providing the key value of 4 the expected result equals the number value 2.
  • providing the key value of 3 the expected result equals the number value 1.

7 thoughts on “Within an array of objects how does one find an object by a certain key name?”

  1. A valid approach was to search the array by its find method. The callback method then needs to implement the matching criteria, which is … does the currently processed array item has the key, one is looking for

    obj => obj.hasOwnProperty(key)
    

    find then does return either the (first) matching object or it returns the undefined value. For the latter case, in order to prevent accessing a property of undefined, one might use the optional chaining/?. operator

    A final solution then might look similar to the next provided one …

    const sampleList = [{
      '2': [1, 3],
    }, {
      '3': [1, 4],
    }, {
      '4': [2, 6],
    }];
    
    function getFirstItemOfObjectByKey(arr, key) {
      return (arr.find(obj =>
        obj.hasOwnProperty(key)
      ))?.[key][0];
    }
    
    console.log(
      getFirstItemOfObjectByKey(sampleList, 4) // expected: 2
    );
    console.log(
      getFirstItemOfObjectByKey(sampleList, 3) // expected: 1
    );
    console.log(
      getFirstItemOfObjectByKey(sampleList, 1) // expected: undefined
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Reply

Leave a Comment