-
Notifications
You must be signed in to change notification settings - Fork 1
/
pickObject.js
36 lines (34 loc) · 897 Bytes
/
pickObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const hasValue = (val) => {
return !["null", "undefined", null, undefined, ""].includes(val);
};
const judageType = (val) =>
val === undefined ||
val === null ||
val === "" ||
["[]", "{}"].includes(JSON.stringify(val));
const filterObject = (ob) => {
console.log("ob", ob);
const val = Array.isArray(ob) ? ob.filter((key) => hasValue(key)) : ob;
console.log("val", val);
return Object.keys(val).length > 0
? Object.keys(val).reduce(
(acc, key) => {
const value = val[key];
if (!judageType(value)) {
acc[key] = typeof value === "object" ? filterObject(value) : value;
}
return acc;
},
Array.isArray(val) ? [] : {}
)
: undefined;
};
const ret = filterObject({
a: {
b: {
c: [undefined, { name: "bbb" }],
// d: "2",
},
},
});
console.log("ret", JSON.stringify(ret));