Skip to content

Instantly share code, notes, and snippets.

@helloncanella
Created November 13, 2019 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helloncanella/0b5ad154b12bbeae25ed90327896be7e to your computer and use it in GitHub Desktop.
Save helloncanella/0b5ad154b12bbeae25ed90327896be7e to your computer and use it in GitHub Desktop.
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