Javascript search for an object key in a set

前端 未结 6 742
太阳男子
太阳男子 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:57

    You may just want a Set of names:

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

    If you want to get an object by name,thats what a Map is for:

    let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
    
    let map = new Map(myObjects.map(el=>[el.name,el]));
    console.log(map.get("a"));
    

提交回复
热议问题