Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 424
bula Avatar asked Jan 23 '26 01:01

bula


1 Answers

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.

like image 98
MD Sayem Ahmed Avatar answered Jan 24 '26 20:01

MD Sayem Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!