Is there a way to get the value of
{
"first": "first-string",
"second-array": [
{
"first-Obj": 2
}
]
}
is there a way to get or update the values by using a path like string
ex: to change the first-obj's value to 1000
changeTheValueAt('second-array/0/firstObj', 1000)
is there any function like above changeTheValueAt or a method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With