当面对此种数据,层层for...in遍历到人已麻
const deepObj = {
"tag": "updated",
"scene": "qcvWec",
"models": {
"1c8f0a6e44a255cdce1ccd7d0d9ae42e394d6a96": {
"grids": {
"TQKPCt3n": {
"status": {
"gridType": "CHUTE",
"status": "CLOSE"
}
}
}
}
}
}
一句话:for...of + 解构赋值,直接遍历对象 entries 并解构 key 和 value 的属性
const models = deepObj.models;
for (let [_model, { grids }] of Object.entries(models)) {
for (let [grid, { status }] of Object.entries(grids)) {
console.log(grid,' ',status); // TQKPCt3n { gridType: 'CHUTE', status: 'CLOSE' }
}
}
详细解释:
假设 models
是一个对象,例如:
const models = {
modelA: { grids: { ... }, other: 123 },
modelB: { grids: { ... }, other: 456 },
};
Object.entries(models)
会得到:
[
['modelA', { grids: {...}, other: 123 }],
['modelB', { grids: {...}, other: 456 }]
]
此种遍历
for (let [_model, { grids }] of Object.entries(models)) {
// _model 是 key,比如 'modelA'
// { grids } 是 value 的解构,直接拿到 grids 属性
}
_model
:对象的 key(如 'modelA'){ grids }
:对象的 value 的解构,直接拿到 value 里的grids
属性
总结
这种写法可以直接拿到对象的 key 和 value 的某个属性,简洁高效。
等价于:
for (let entry of Object.entries(models)) {
let _model = entry[0];
let grids = entry[1].grids;
// ...
}