0

I have a nested javascript object

var x={
    y1:{
        z1:"some value 4 y1z1",
        z2:"some value 4 y1z2",
    },
    y2:{
        z1:"some value 4 y2z1",
        z2:"some value 4 y2z2",
    }
}

Now I have a function to change a property of this object by passing the field name as string and a value as shown below.

function setproperty4X(field,value){
    x[field]=value;
}

But if I give a 2 level deep property name to update the value it doesn't set the value of that deeper property but creates a new one. For eg if I give "y1.z1" instead if setting z1 of y1 in x it creates a property y1.z1 in x. See below code for more detail. Also see this fiddle

setproperty4X("y1.z1","new value for y1.z1");

console.log(x.y1.z1) // doesn't reflect the new value.
console.log(x['y1']['z1']); // neither does this

console.log(x['y1.z1']) // but this shows the new value
BiJ
  • 1,639
  • 5
  • 24
  • 55
  • There's no build-in way to do this. You need to write your own function to do this. Split on `.` then loop through the keys to traverse the object. Now, write some code to attempt this and show us what you've managed to write. – slebetman Aug 06 '15 at 10:05
  • 1
    @BiJ Try this http://jsfiddle.net/442c6xkk/ – Oleksandr T. Aug 06 '15 at 10:07

0 Answers0