问题
How to enumerate complex javascript object to get property paths to plain values?
In example if object is:
let complex = {
person: {name: 'mat', age: 31},
car: {
model: 'Volsan',
engine: 'large',
doors:[
{ side:'right front', color: 'blue' },
{ side:'left rear', color: 'red' }
]
}
};
and outcome would be like:
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"
eg. it would be reverse _.at from lodash: https://lodash.com/docs/4.17.5#at
回答1:
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);
来源:https://stackoverflow.com/questions/49125398/how-to-enumerate-complex-javascript-object