Open senfish opened 3 years ago
刚开始,首先想到了for ... in
,
function flatten(obj) {
let map = {};
const df = (obj, path = "", parentType = 'object') => {
for(let key in obj) {
if(Object.hasOwnProperty.call(obj, key)) {
let rePath = ''
if (parentType === 'object') {
rePath = `${path}.${key}`
} else if (parentType === 'array') {
rePath = `${path}[${key}]`
} else {
rePath = key;
}
if(Array.isArray(obj[key])) {
df(obj[key], rePath, 'array')
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
df(obj[key], rePath, 'object')
} else {
map[rePath] = obj[key]
}
}
}
}
df(obj, '', '');
console.log(map);
}