Javascript search for an object key in a set

前端 未结 6 739
太阳男子
太阳男子 2021-01-14 09:46

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         


        
6条回答
  •  梦毁少年i
    2021-01-14 09:54

    Not in that way, that would look for the specific object you're passing in, which isn't in the set.

    If your starting point is an array of objects, you don't need a Set at all, just Array.prototype.find:

    let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
    let found = myObjects.find(e => e.name === "a");
    console.log(found);

    If you already have a Set and want to search it for a match, you can use its iterator, either directly via for-of:

    let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
    let mySet = new Set(myObjects);
    let found = undefined; // the `= undefined` is just for emphasis; that's the default value it would have without an initializer
    for (const e of mySet) {
      if (e.name === "a") {
        found = e;
        break;
      }
    }
    console.log(found);

    ...or indirectly via Array.from to (re)create (the)an array, and then use find:

    let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
    let mySet = new Set(myObjects);
    let found = Array.from(mySet).find(e => e.name === "a");
    console.log(found);


    If it's something you need to do often, you might give yourself a utility function for it:

    const setFind = (set, cb) => {
      for (const e of set) {
        if (cb(e)) {
          return e;
        }
      }
      return undefined; // undefined` just for emphasis, `return;`
                        // would do effectively th same thing, as
                        // indeed would just not having a `return`
                        // at at all
    }
    
    let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
    let mySet = new Set(myObjects);
    let found = setFind(mySet, e => e.name === "a");
    console.log(found);

    You could even put that on Set.prototype (making sure it's non-enumerable), but beware of conflicting with future additions to Set (for instance, I wouldn't be at all surprised if Set.prototype got a find method at some point).

提交回复
热议问题