如何枚举复杂的javascript对象 [英] How to enumerate complex javascript object
本文介绍了如何枚举复杂的javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何枚举复杂的javascript对象以获取纯值的属性路径?
How to enumerate complex javascript object to get property paths to plain values?
例如,如果对象是:
let complex = {
person: {name: 'mat', age: 31},
car: {
model: 'Volsan',
engine: 'large',
doors:[
{ side:'right front', color: 'blue' },
{ side:'left rear', color: 'red' }
]
}
};
结果将是:
complex.person.name
complex.person.age
complex.car.model
complex.car.engine
complex.car.doors[0].side
complex.car.doors[0].color
complex.car.doors[1].side
complex.car.doors[1].color
以便只有那些值结束图形"
so that there would be only those values that are "ending the graph"
例如它会与lodash反向_.at: https://lodash.com/docs/4.17. 5#at
eg. it would be reverse _.at from lodash: https://lodash.com/docs/4.17.5#at
推荐答案
此递归解决方案使用 Array.map()
和 Array.concat()
和传播:
This recursive solution uses Array.map()
, and Object.keys()
to add the keys to a base path. Then we flatten the resulting array using Array.concat()
and spread:
const complex = {
person: {name: 'mat', age: 31},
car: {
model: 'Volsan',
engine: 'large',
doors:[
{ side:'right front', color: 'blue' },
{ side:'left rear', color: 'red' }
]
}
}
const addDot = (b, s) => `${b}${b && '.'}${s}`
const wrapBrackets = (b, s) => `${b}[${s}]`
const mapPaths = (obj, base = '') => {
if(typeof obj !== 'object') {
return base;
}
const formatter = Array.isArray(obj) ? wrapBrackets : addDot;
return [].concat(...Object.keys(obj)
.map((key) => mapPaths(obj[key], formatter(base, key))))
};
const result = mapPaths(complex)
console.log(result);
这篇关于如何枚举复杂的javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文