Get the values by giving key order as a string path JSON Get the values by giving key order as a string path JSON json json

Get the values by giving key order as a string path JSON


Use the following function for that -

function changeTheValueAt(obj, path, value) {    var parts = path.split("/"),        final = obj[parts[0]],        i;    for (i = 1; i < parts.length; i++) {        if (i + 1 < parts.length) {            final = final[parts[i]];        }        else {            final[parts[i]] = value;        }    }}

and then call it like this -

var ob = {    "first": "first-string",    "second-array": [        {            "first-Obj": 2        }    ]};changeTheValueAt(ob, "second-array/0/first-Obj", 1000)alert(ob["second-array"][0]["first-Obj"]);

JSFiddle Demo.


Because second-array is an array, you can't access it by name. You can access it by index or you can iterate over and find a value and change it when found.

var yourObj = {   "first": "first-string",   "second-array": [      {         "first-Obj": 2      }    ]};yourObject.second-array[0].first-Obj = 1000;

You could do something like:

var changeFirstObj = function(node1, node2, new val){   yourObj[node1].forEach(o, i){     for(var prop in o){       if(prop == node2){          o[node2]=newVal;        }   };   changeFirstObj('second-array', 'first-Obj', 1000);  

But that's not really very flexible.