I'm trying to create a JS object dynamically providing a key and a value. The key is in dot notation, so if a string like car.model.color is provided the generated object would be:
{
  car: {
    model: {
      color: value;
    }
  }
}
The problem has a trivial solution if the key provided is a simple property, but i'm struggling to make it work for composed keys.
My code:
function (key, value) {
  var object = {};
  var arr = key.split('.');                                   
  for(var i = 0; i < arr.length; i++) {
    object = object[arr[i]] = {};
  }
  object[arr[arr.length-1]] = value;
  return object;
}
                your slightly modified code
function f(key, value) {
  var result = object = {};
  var arr = key.split('.');                                   
  for(var i = 0; i < arr.length-1; i++) {
    object = object[arr[i]] = {};
  }
  object[arr[arr.length-1]] = value;
  return result;
}
In the loop you should set all of the props but the last one. Next set the final property and all set.
If you're using lodash you could use _.set(object, path, value)
const obj = {}
_.set(obj, "car.model.color", "my value")
console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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