Open LuckyWinty opened 4 years ago
let str = ''
let o = {}
function objFlatten (obj) {
Object.keys(obj).map(item => {
if (Object.prototype.toString.call(obj[item]) === '[object Object]') {
str += item + '.'
objFlatten(obj[item])
} else if (Object.prototype.toString.call(obj[item]) === '[object Array]') {
obj[item].forEach((ele, index) => o[item+`[${index}]`] = ele)
} else {
str += item
o[str] = obj[item]
str = ''
}
})
}
参考深拷贝的实现,区分不同的对象类型
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) : arr.slice();
};
转自MDN
function objFlat(obj) {
let res = {}
const __flat = (obj, key) => {
if (notArrAndObj(obj)) {
res[key] = obj
return
}
isArray = Array.isArray(obj)
for (let k in obj) {
let keyString = ''
if (!key) {
keyString = k
} else {
if (isArray) {
keyString = `${key}[${k}]`
} else {
keyString = key + '.' + k
}
}
__flat(obj[k], keyString)
}
}
__flat(obj, '')
return res
}
function notArrAndObj(obj) {
return Object.prototype.toString.call(obj) !== '[object Array]' && Object.prototype.toString.call(obj) !== '[object Object]'
}