Sunny
Sunny

Reputation: 10075

How to set value to a property in a Javascript object, which is identified by an array of keys

If there is a Javascript object with multiple levels, as in:

   myObject = {
         a: 12,
        obj11: {
                obj111: 'John',
                b:13,
                obj1111: { a:15,
                           b: 35 }
        obj21: { 
                a:15,
                b:16 }
         }

I want to write a function to which is passed the object, an array of keys and the value to be assigned to the matched property.

 function myFunc (myObj,myArr, newValue) {
   ...
  }
  myFunc(myObject, ['obj11', 'obj1111'], {z:12});
  console.log(myObject.obj11.obj1111);

Should display {z:12}. Assume that the keys in the array are always correct.

Upvotes: 2

Views: 61

Answers (2)

Sudheesh S Krishna
Sudheesh S Krishna

Reputation: 39

function myFunc(myObj,myArr,newValue){
  var temp=myObj;
  for(var I=0;I<myArr.length;I++){
    temp=temp[myArr[I]];
  }
  temp=newValue;
};

Update: This is a classic example of how you can access properties from an object in JavaScript. You may, for simplicity, consider object as an array of properties. Now try and access the required property as if it is the index of the array. If u have a nested object, consider it as a nested array.

Eg: console.log(myObj['obj11']['obj1111']);

The above code will display { a:15, b: 35 }, before running the myFunc() and will display {z:12} after running it.

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use reduce() method to find nested object and if its found then you can use Object.assign() to add new property.

var myObject = {"a":12,"obj11":{"obj111":"John","b":13,"obj1111":{"a":15,"b":35},"obj21":{"a":15,"b":16}}}

function myFunc (myObj, myArr, newValue) {
  myArr.reduce(function(r, e, i, arr) {
    if(!arr[i+1] && typeof r[e] == 'object') Object.assign(r[e], newValue);
    return r[e] || {}
  }, myObj)
}

myFunc(myObject, ['obj11', 'obj1111'], {z:12});
console.log(myObject)

Update If you just want to change value of nested property then you can use something like this.

var myObject = {"a":12,"obj11":{"obj111":"John","b":13,"obj1111":{"a":15,"b":35},"obj21":{"a":15,"b":16}}}

function myFunc (myObj, myArr, newValue) {
  myArr.reduce(function(r, e, i, arr) {
    if(!arr[i+1] && r[e]) r[e] = newValue
    return r[e] || {}
  }, myObj)
}

myFunc(myObject, ['obj11', 'obj1111'], {z:12});
console.log(myObject)

Upvotes: 3

Related Questions