Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find object by key in array of object

Hello this is array of objects

  const raceId = '1004'
  const array =  [
    {
      '1004': { brackets: { '18': [Object], '19': [Object], '20': [Object] } }
    },
    {
      '999': { brackets: { '1': [Object], '2': [Object], '3': [Object] } }
    }
  ] 

So i am trying to return just a

{ brackets: { '18': [Object], '19': [Object], '20': [Object] } }

I have tried to use reduce(), map(), find() but not getting desired output. For example i have tried.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const reduced = raceScoringConfigGroups.reduce((acc, key) => {
   if (Object.keys(key)[0] === raceId) {
     return key[raceId]
   }
  }, {})

But for some reason getting undefined, can someone help me just a little bit, not sure what i am doing wrong. I don’t like solutions with forEach or for loops, trying to write oneliner.

>Solution :

The value you return in the reduce() callback is used as the accumulator in the next iteration. Since you don’t return anything when the key doesn’t match raceId, your code will only work if the matching key is the last element of the array.

Use find() rather than reduce(), and then get the property from that.

const found = raceScoringConfigGroups.find(el => el[raceId]);
const reduced = found?.[raceId];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading