Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create objects dynamically out of a dot notation like string

Tags:

javascript

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;
}
like image 347
jorgepr Avatar asked Nov 28 '22 14:11

jorgepr


2 Answers

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.

like image 139
marcinn Avatar answered Dec 07 '22 23:12

marcinn


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>
like image 33
DannyFeliz Avatar answered Dec 08 '22 00:12

DannyFeliz