简体   繁体   English

迭代深度嵌套的对象

[英]Iterating over deeply nested objects

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.而且我需要能够遍历此数据中的每个项目,找到 ID === 已知 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.我唯一能想到的是一个 for-In 循环,但在循环 object 之后,我必须在 arrays 上进行 map,这样看起来不是很干净。

Is there any method that is clean for handling iterating over such deeply nested data?是否有任何方法可以干净地处理对如此深度嵌套的数据的迭代?

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. Array.prototype.find有助于在数组中找到 object, Object.values将对象的所有值作为数组返回,而Array.prototype.flat有助于展平 ZA3CBC3F9D0CE2F2C19554 数组

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 .下面的实现还使用Arrow function 表达式作为find的回调 function 以及destructuring_assignment,该解构赋值用于从 ZA8CFDE6331BD59EB2AC96F8911Z 中解压缩作为参数传递给 C4B6 的回调字段

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM