-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
34 lines (29 loc) · 974 Bytes
/
utils.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
export function pick(obj, ...props) {
const objKeys = Object.keys(obj);
const result = {};
for (const key of objKeys) {
for (const prop of props) {
let [oldPropKey, newPropKey] = prop.split(':');
if (!newPropKey) newPropKey = oldPropKey;
if (key === oldPropKey) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
result[newPropKey] = pick(obj[oldPropKey], ...props);
} else if (Array.isArray(obj[key])) {
result[newPropKey] = obj[oldPropKey].map(item => pick(item, ...props));
} else {
result[newPropKey] = obj[oldPropKey];
}
}
}
}
return result;
}
// const example = {
// name: 'Denis',
// age: 19,
// head: {
// iq: 2,
// isGlassed: true
// }
// }
// console.log(pick(example, 'name', 'head', 'isGlassed:isDebil'));