Search code examples
javascriptecmascript-5

Access nested object property and update its value through Generic method


I want create a generic method which will access a nested object property and update its value passed as argument.

This is my data structure
 var student = {
  name: 'Tom',
  address: {
    pincode: 43301,
    street: '12th Main',
    city: 'Some city',
  },
  marks: {
    sub1: 111,
    sub2: 222
  }
}

This is my skeleton of the generic method

updatProperty(student, 'marks.sub1', 125) {
  // this method should return student object with marks.sub1 to be 125
}

I have refereed this link , but this will only return me a value


Solution

  • You could do this with reduce method, where you check if current value exists and if length of your string key is equal to current element and then change value.

    var student = {"name":"Tom","address":{"pincode":43301,"street":"12th Main","city":"Some city"},"marks":{"sub1":111,"sub2":222}}
    
    function updatProperty(obj, key, value) {
      key.split('.').reduce((r, e, i, a) => {
        if (r[e] && a.length - 1 == i) r[e] = value
        return r[e] || {}
      }, obj)
    }
    
    updatProperty(student, 'marks.sub1', 125);
    console.log(student)