[Solved] Stop overriding object once it has been set dynamically [closed]


The issue here is that you’re not saving a reference to the original object… you’re overwriting your object variable in the for-loop and then returning the final value of that variable. Perhaps you should add a line like:

var current = object;

and then use current instead of object in the rest of your function. Then you can return object and it will be still be a reference to your original input.

Edit: OP wasn’t using the return value to begin with, so my original solution didn’t help. The problem was that OP was passing in related sets of keys (“price.minPrice”, “price.maxPrice”) and the function was overwriting the value of the initial shared key (“price”). The solution is to check if an object already exists at the key in question before assigning an empty one.

function populateObject(obj, keyString, value) {
    var keys = keyString.split('.'),
        curr = obj;

    for (var i = 0; i < keys.length - 1; i++) {
        if (!curr[keys[i]]) curr[keys[i]] = {};
        curr = curr[keys[i]];

    }
    curr[keys[keys.length - 1]] = value;

    return obj;
}

var myObject = { foo: 'bar' };
var result = populateObject(myObject, 'some.nested.keys', 'something');

result = populateObject(result, 'some.nested.other', 'test');

console.log(result === myObject);
console.log(result.foo === 'bar');
console.log(result.some.nested.keys === 'something');
console.log(result.some.nested.other === 'test');

16

solved Stop overriding object once it has been set dynamically [closed]