[Solved] set object property with dot notation without using eval


You need just to add the variable name in front of the properties.

a.data.clients[1].name="Johny";

If you have a string, you could split the path and reduce the path by walking the given object. If no Object exist, create a new property with the name, or an array. Later assign the value.

function setValue(object, path, value) {
    var way = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'),
        last = way.pop();

    way.reduce(function (o, k, i, kk) {
        return o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {});
    }, object)[last] = value;
}

const a = { data: { clients:[{ id:1, name:'Tom' }, { id:2, name:'John' }, { id:1, name:'Lucy' }] } };

setValue(a, 'data.clients[1].name', 'Johny');
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }

4

solved set object property with dot notation without using eval