xref: /expo/packages/@expo/cli/src/utils/obj.ts (revision 0ee75920)
1/** `lodash.get` */
2export function get(obj: any, key: string): any | null {
3  const branches = key.split('.');
4  let current: any = obj;
5  let branch: string | undefined;
6  while ((branch = branches.shift())) {
7    if (!(branch in current)) {
8      return null;
9    }
10    current = current[branch];
11  }
12  return current;
13}
14
15/** `lodash.set` */
16export function set(obj: any, key: string, value: any): any | null {
17  const branches = key.split('.');
18  let current: any = obj;
19  let branch: string | undefined;
20  while ((branch = branches.shift())) {
21    if (branches.length === 0) {
22      current[branch] = value;
23      return obj;
24    }
25
26    if (!(branch in current)) {
27      current[branch] = {};
28    }
29
30    current = current[branch];
31  }
32  return null;
33}
34
35/** `lodash.pickBy` */
36export function pickBy<T>(
37  obj: { [key: string]: T },
38  predicate: (value: T, key: string) => boolean | undefined
39) {
40  return Object.entries(obj).reduce((acc, [key, value]) => {
41    if (predicate(value, key)) {
42      acc[key] = value;
43    }
44    return acc;
45  }, {} as { [key: string]: T });
46}
47