Javascript search for an object key in a set

Viewed 27166

Is it possible to use the javascript "Set" object to find an element with a certain key? Something like that:

let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let mySet = new Set(myObjects);
console.log(mySet.has({"name":"a"}));
7 Answers

Actually a response to Efficiently find an item in a Set but they've closed it as a duplicate #ftw

An alternative approach:


class ArraySet extends Set {

    find(predicate) {
        for(var x of this)
            if (predicate(x)) return x;
        return undefined;
    },

    ... other Array.prototype stuff here

}

const things = new ArraySet([
    { x: 1 },
    { y: 2 }
]);

const found = things.find(item => item.y === 2);

If you want your solution to be performant, use Map instead of Set. If your Set is not that big you can go with T.J. Crowder solution and convert Set to Array then filter and vice versa.

let myObjects = [['a',{"name":"a", "value":0}], ['b',{"name":"b", "value":1}],['c',{"name":"c", "value":2}]];
let myMap = new Map(myObjects);
console.log(myMap.has('a'));

      var myObj = { "A": "1", "B": "2", "C": "3" }
      var objLength = Object.keys(myObj).length

      var firstKeyOfObject = Object.keys(myObj)[0]
      var firstValueOfObject = myObj[Object.keys(myObj)[0]]
      var lastKeyOfObject = Object.keys(myObj)[objLength - 1]
      var lastValueOfObject = myObj[Object.keys(myObj)[objLength - 1]]
      

      console.log('firstKeyOfObject', firstKeyOfObject)
      console.log('firstValueOfObject', firstValueOfObject)
      console.log('lastKeyOfObject', lastKeyOfObject)
      console.log('lastValueOfObject', lastValueOfObject)
Related