Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic deep setting for a JavaScript object [duplicate]

Given a string for a object property path, how do I set this property dynamically.

Given this sample object:

var obj = {     a: {         b: [ { c: 'Before' } ]     } }; 

It should be able to set the value with a helper function like this:

setToValue(obj, 'After', 'a.b.0.c'); 

I tried it with the following code. But parent is a copy if the variable not a reference.

function setToValue(obj, value, path) {     var arrPath = path.split('.'),         parent = obj;      for (var i = 0, max = arrPath.length; i < max; i++) {         parent = parent[arrPath[i]];     }      parent = value; } 
like image 304
Alex Avatar asked Jul 27 '11 10:07

Alex


People also ask

How do you make a deep copy in JavaScript?

Copy an Object With Object. assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

How do you copy properties from one object to another JS?

The Object. assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. In the code above, we changed the value of the property 'b' in objCopy object to 89 and when we log the modified objCopy object in the console, the changes only apply to objCopy .


2 Answers

a) What's wrong with a simple a.b[0].c = 'After'?

As for the method:

function setToValue(obj, value, path) {     var i;     path = path.split('.');     for (i = 0; i < path.length - 1; i++)         obj = obj[path[i]];      obj[path[i]] = value; } 

Here the JSFiddle: http://jsfiddle.net/QycBz/24/

like image 61
Tigraine Avatar answered Oct 09 '22 06:10

Tigraine


Here is a full solution.

Also creates objects if they don't exist.

function setValue(obj, path, value) {   var a = path.split('.')   var o = obj   while (a.length - 1) {     var n = a.shift()     if (!(n in o)) o[n] = {}     o = o[n]   }   o[a[0]] = value }  function getValue(obj, path) {   path = path.replace(/\[(\w+)\]/g, '.$1')   path = path.replace(/^\./, '')   var a = path.split('.')   var o = obj   while (a.length) {     var n = a.shift()     if (!(n in o)) return     o = o[n]   }   return o } 
like image 27
Dieter Gribnitz Avatar answered Oct 09 '22 04:10

Dieter Gribnitz