Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[JS]Change multi level object value

var obj = {
    a:{
        value: 1
    }
}

var str = 'a.value';

obj[str] = 'work';
console.log(obj);

I have this code, I need to change the value of the object using the string

like image 653
Yauheni Kastsiukevich Avatar asked Jun 25 '26 09:06

Yauheni Kastsiukevich


1 Answers

Solution with recursion

var obj = {
    a: {
        value: 1
    }
}

var str = 'a.value';

function change(obj, prop, newValue) {
    var a = prop.split('.');
    return (function f(o, v, i) {
        if (i == a.length - 1) {
            o[a[i]] = v;
            return o;
        }
        return f(o[a[i]], v, ++i);
    })(obj, newValue, 0);
}

var result = change(obj, str, 'work');

console.log(JSON.stringify(obj, 0, 2));
like image 88
isvforall Avatar answered Jun 26 '26 23:06

isvforall



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!