Last active
March 21, 2022 16:01
-
-
Save htaketani/54a72f886db9cc0cfe95e8ae307a5e2b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * pick deeply from object | |
| * | |
| * usage: | |
| * const obj = { | |
| * a: 1, | |
| * b: { ba: 21, bb: 22 }, | |
| * c: [ | |
| * { ca: 311, cb: { cba: 3121, cbb: 3122 } }, | |
| * { ca: 321, cb: { cba: 3221, cbb: 3222 } }, | |
| * ], | |
| * d: 4, | |
| * } | |
| * pickDeep(obj, ['a', ['b', ['ba']], ['c', ['ca', ['cb', ['cba']]]]]) | |
| * // -> return { a: 1, b: { ba: 21 }, c: [ { ca: 311, cb: { cba: 3121 } }, { ca: 321, cb: { cba: 3221 } } ] } | |
| * | |
| * @param {Object} obj | |
| * @param {[string|Array]} rules // 'key' or ['key', ['childKey1', ...]] | |
| * @return {Object} | |
| */ | |
| export const pickDeep = (obj, rules) => | |
| obj && rules.reduce((res, rule) => { | |
| const [key, nestedRules] = ((typeof rule) === 'string') ? [rule, null] : rule | |
| const val = obj[key] | |
| if (key in obj) { | |
| if (nestedRules) { | |
| if (Array.isArray(val)) { | |
| // nest for collection | |
| res[key] = val.map(o => pickDeep(o, nestedRules)) | |
| } else if (val !== 'null' && typeof val === 'object') { | |
| // nest for object | |
| res[key] = pickDeep(val, nestedRules) | |
| } else { | |
| res[key] = val | |
| } | |
| } else { | |
| res[key] = val | |
| } | |
| } | |
| return res | |
| }, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment