Search code examples
javascriptecmascript-6ecmascript-5

Find a Value in a Dictionary with a certain Property


Say I have a dictionary like

objDict = {
  id1 : { name: 'someObj1', id: 'someId1' },
  id2 : { name: 'someObj2', id: 'someId2' },
  id3 : { name: 'someObj3', id: 'someId3' },
}

If I wanted to search for the property "someId2" of the "id" property in Values of that dictionary.. how would I be able to grab the the whole object after finding it?

I really can't think of a good way to do it outside of iterating the dictionary with a for-in loop. I was thinking of using Object.values() but even then I can't think of a way of using that to grab the whole object that contains someId2.. I would only be able to determine if that property existed.

I was just wondering if there was a better way than a for-in loop. Thanks


Solution

  • you can just get all the keys using Object.keys(), then iterate over these and select the object you want based on the required id.

    var objDict = {
      id1 : { name: 'someObj1', id: 'someId1' },
      id2 : { name: 'someObj2', id: 'someId2' },
      id3 : { name: 'someObj3', id: 'someId3' },
    };
    var obj;
    
    Object.keys(objDict).forEach(x => obj = objDict[x].id === 'someId2' ? objDict[x]: obj);
    
    console.log(obj);