Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value in nested object

Tags:

javascript

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

like image 311
Antoni Avatar asked Jun 18 '26 02:06

Antoni


1 Answers

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>
like image 65
tex Avatar answered Jun 20 '26 16:06

tex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!