I try to set a value into nested array by a key.
My Object looks like
var Obj = {
key1: {
key2: value,
}
}
I try to set key1 by key1.key2 like
const name = `key1.key2`
Obj[name] = value
I knew I need to do it like Obj['key1']['key2'] but I get only a string which looks like key1.key2
If you don't mind using a library, Ramda and lodash offer helper functions that make this sort of operation very simple
With Ramda (slightly more verbose than lodash for this specific operation, but I prefer Ramda to lodash):
const Obj = {
key1: {
key2: 1,
}
}
const name = `key1.key2`
console.log(
R.assocPath(name.split('.'), 2, Obj)
)
// --> { key1: { key2: 2 } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
With lodash:
const Obj = {
key1: {
key2: 1,
}
}
const name = `key1.key2`
console.log(
_.set(Obj, name, 2)
)
// --> { key1: { key2: 2 } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With