Last active
August 16, 2018 05:41
-
-
Save Alexgalinier/d86734ee94755073be362ccc838be212 to your computer and use it in GitHub Desktop.
Deep Pick
This file contains 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
const typeOf = _ => Object.prototype.toString.call(_); | |
// Result can be used with db.collection.find : PARTIALLY | |
const arrayToSchema = keys => | |
keys.reduce((schema, _) => { | |
if (_.indexOf('.') > -1) { | |
const [key, rest] = _.split('.'); | |
schema[key] = { | |
...schema[key], | |
...arrayToSchema([rest]), | |
}; | |
} else { | |
schema[_] = true; | |
} | |
return schema; | |
}, {}); | |
const pick = (obj, schema) => | |
Object.keys(schema).reduce((acc, key) => { | |
switch (typeOf(obj[key])) { | |
case '[object Object]': | |
acc[key] = pick(obj[key], schema[key]); | |
break; | |
case '[object Array]': | |
acc[key] = obj[key].map(_ => pick(_, schema[key])); | |
break; | |
default: | |
acc[key] = obj[key]; | |
} | |
return acc; | |
}, {}); | |
const obj1 = { | |
key1: 1, | |
key2: 2, | |
key3: 3, | |
}; | |
const obj2 = { | |
key1: 1, | |
key2: 2, | |
key3: [ | |
{ key5: 5, key6: 6, key7: 7 }, | |
{ key5: 8, key6: 9, key7: 10 }, | |
{ key5: 11, key6: 12, key7: 13 }, | |
], | |
key4: 4, | |
}; | |
const obj3 = { | |
key1: 1, | |
key2: { | |
key3: 3, | |
key4: 4, | |
key5: 5, | |
}, | |
}; | |
console.log(pick(obj1, arrayToSchema(['key1', 'key3']))); | |
console.log( | |
pick(obj2, arrayToSchema(['key1', 'key3.key5', 'key3.key6', 'key4'])), | |
); | |
console.log(pick(obj3, arrayToSchema(['key1', 'key2.key3', 'key2.key4']))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment