Javascript search for an object key in a set

前端 未结 6 814
太阳男子
太阳男子 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条回答
  •  甜味超标
    2021-01-14 09:56

    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);
    
    

提交回复
热议问题