Created
November 13, 2019 17:39
-
-
Save helloncanella/0b5ad154b12bbeae25ed90327896be7e to your computer and use it in GitHub Desktop.
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
import _ from "lodash" | |
/** | |
* consider the object | |
* | |
* const obj = { | |
* key1: value1 | |
* key2: value2 | |
* "key3,key4,key5": {key3: value3, key4: value4} | |
* } | |
* | |
* spreadValuesWithKeySeparatedByComma(obj) outputs | |
* | |
* { | |
* key1: value1, | |
* key2: value2, | |
* key3: value3, | |
* key4: value4, | |
* key5: undefined | |
* } | |
* | |
*/ | |
export default function spreadValuesWithKeySeparatedByComma(obj) { | |
if (!_.isPlainObject(obj)) return obj | |
const clone = JSON.parse(JSON.stringify(obj)) | |
return _.entries(clone).reduce((acc, [key, value]) => { | |
const isSeparatedByComma = key.split(",").length > 1 | |
if (isSeparatedByComma && _.isPlainObject(value)) { | |
const keys = key.split(",") | |
acc = { ...acc, ..._.pick(value, keys) } | |
} else { | |
acc[key] = value | |
} | |
return acc | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment