例如,这是我发现的使按键平坦的功能
const keys = flattenKeys({a: { b: 1, c: 1}});
退货
{ 'a.b': 1, 'a.c': 1 }
但是对于这个输入
const keys = flattenKeys({a: { b: 1, c: () => {}}});
它给我
{ 'a.b': 1 }
我们可以看到
a.c
丢失了export const flattenKeys = (obj: Record<string, any> | any[], path: string[] = []) =>
!isObject(obj) ? { [path.join('.')]: obj } : reduce(obj, (cum, next, key) => merge(cum, flattenKeys(next, [...path, key])), {});
我试图添加
!isObject(obj) && isFunction(obj) ...
,但似乎无法正常工作预期产量:
{
'a.b': 1,
'a.c': () => {}
}
@编辑:
isObject,reduce,merge来自
lodash
包 最佳答案
将!isObject(obj) ?
更改为!isPlainObject(obj) ?
以仅排除普通对象:
const flattenKeys = (obj: Record < string, any > | any[], path: string[] = []) =>
!_.isPlainObject(obj) ? {
[path.join('.')]: obj
} : _.reduce(obj, (cum, next, key) => _.merge(cum, flattenKeys(next, [...path, key])), {});
const keys = flattenKeys({
a: {
b: 1,
c: () => {}
}
});
console.log(keys);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>