This question has already been answered:

Object properties can be obtained as follows: obj['property'] . But what if the properties need to be obtained from a string (for example, 'pink.floyd.songs' ), we split('.') And get something like: obj['pink']['floyd']['songs'] . The problem is that we do not know prematurely how many investments there will be (the line could be, for example, like this: 'elbow.songs' ). How can you work with the properties of objects in this case? It is necessary not only to get the value of a certain Holy Island, but also to assign it some value. Those. we get some string as input, break it into an array of property names, we need to get something like this: obj['prop1']['prop2']['prop...'] = someValue . Based on the answer, I created a function for my task, who can come in handy:

 function props(obj, arr) { var result = obj; for (var c = 0, l = arr.length; c < l - 1; c++) { result = result[arr[c]]; } return {obj: result, prop: arr[arr.length - 1]}; } var o = props(obj, props); o.obj[o.prop] = 'Some Value'; 

Reported as a duplicate by Grundy , cheops , aleksandr barakin , Streletz , user194374 Jun 22 ', at 5:55 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • lodash.com/docs#get - Alexey Ten
  • I'm 100% sure there was such a question - Grundy
  • The problem is not very clear. With this formulation, I can assume to calculate the size of the array. - user206425
  • Your decision needs to be in the form of a response - Grundy
  • o.obj[o.prop] = 'Some Value'; - I would send inside. And so, it seems the question already has an answer. What is the question? - Qwertiy

2 answers 2

What could be easier?

 var obj = ...; var names = "...".split("."); for (var i = 0; i < names.length; ++i) obj = obj[names[i]]; console.log(obj); 
  • tadam :-) question update: now we also need to assign values ​​:-) - Grundy

Here is my decision based on the @kff response:

 function objProps(obj, arr) { var result = obj; for (var c = 0, l = arr.length; c < l - 1; c++) { result = result[arr[c]]; } return {obj: result, prop: arr[arr.length - 1]}; } var o = objProps(obj, props); o.obj[o.prop] = 'Some Value';