const input = {
a: 1,
b: [1, 2, {c: true}, [3]],
d: {e: 2, f: 3},
g: null
}
const output = {
"a": 1,
"b[0]": 1,
"b[1]": 2,
"b[2].c": true,
"b[3][0]": 3,
"d.e": 2,
"d.f": 3
}
function getType (param) {
const match = Object.prototype.toString.call(param).match(/\[object (\w+)\]/)
return match ? match[1] : ''
}
function isvalidVal (val) {
return val !== undefined && val !== null
}
function getNameByRootType (baseKey, key, type) {
if (baseKey == '') return key
if (type == 'Object') {
return `${baseKey}.${key}`
} else if (type == 'Array') {
return `${baseKey}[${key}]`
} else {
return baseKey + key
}
}
// 处理 Object、Array
const flatten = (input, result, baseK = '') => {
const rootTpye = getType(input)
for (const [key, val] of Object.entries(input)) {
if (isvalidVal(val)) {
const keyName = getNameByRootType(baseK, key, rootTpye)
if (typeof val == 'object') {
flatten(val, result, keyName)
} else {
result[keyName] = val
}
}
}
}
const result = {}
flatten(input, result)
console.log(result)
console