Home > OS >  Iterating over deeply nested objects
Iterating over deeply nested objects

Time:01-12

I have data that looks like this:

{
  FL: [{ID: 1, confirmed: true},{ID: 2, confirmed: false}], 
  TX: [{ID: 3, confirmed: true}], 
  NY: [{ID: 4, confirmed: false}, {ID: 5, confirmed: true}]
}

And I need to be able to loop over each item in this data find the one who's ID === a known ID. I'm not sure the best way to approach this.

The only thing that I can come up with is a for-In loop but Id have to map over the arrays after looping over the object so that doesn't seem very clean.

Is there any method that is clean for handling iterating over such deeply nested data?

CodePudding user response:

Array.prototype.find helps one to find an object within an array, and Object.values returns all of an object's values as array, whereas Array.prototype.flat helps flattening an array of arrays.

The beneath implementation also uses an Arrow function expressions as find's callback function together with a destructuring_assignment which is applied for unpacking a field from an object passed as a parameter to the callback.

function findObjectByID(obj, id) {
  return Object
    .values(obj)
    .flat()
    .find(({ ID }) => ID === id);
}

const sampleData = {
  FL: [{ ID: 1, confirmed: true }, { ID: 2, confirmed: false }], 
  TX: [{ ID: 3, confirmed: true }], 
  NY: [{ ID: 4, confirmed: false }, { ID: 5, confirmed: true }],
};

console.log(
  'findObjectByID(sampleData, 2) ...',
  findObjectByID(sampleData, 2)
);
console.log(
  'findObjectByID(sampleData, 3) ...',
  findObjectByID(sampleData, 3)
);
console.log(
  'findObjectByID(sampleData, 5) ...',
  findObjectByID(sampleData, 5)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

Here's a method that preserves the key as well as returning the match.

let obj = {
  FL: [{ID: 1, confirmed: true},{ID: 2, confirmed: false}], 
  TX: [{ID: 3, confirmed: true}], 
  NY: [{ID: 4, confirmed: false}, {ID: 5, confirmed: true}]
}

const findFromId = (obj, id) => {
  for (let x in obj) {
     if (res = obj[x].find(a => a.ID == id)) return { [x]: res }
  }
  return null;
}

console.log(findFromId(obj, 5))

  •  Tags:  
  • Related