0

I have the following function which resets an object with variable depth's deepest value to 0. I want the function to change the property of the object outside the function's scope;

    var object =
        { '1': {
                '10000': { '0': 6, '15': 3, '35': 5, '55': 3, '75': 85 },
            }
        } 

    function resetCounts(obj) {
        for (var el in obj) {
            if (obj.hasOwnProperty(el)) {
                if (typeof obj[el] == 'number') {
                    if (obj[el] > 0) {
                        console.log(obj)
                        console.log(obj[el]);
                        obj[el] = 0;
                        console.log('reset');
                        console.log(obj);
                        console.log(obj[el]);
                    }
                    return;
                }
                resetCounts(obj[el]);
            }
        }
    }

resetCounts(object);

Here is the result in the console:

{ '0': 6, '15': 3, '35': 5, '55': 3, '75': 85 }
6
reset
{ '0': 0, '15': 3, '35': 5, '55': 3, '75': 85 }
0

The expected result is for object to be:

        { '1': {
                '10000': { '0': 0, '15': 0, '35': 0, '55': 0, '75': 0 },
            }
        } 

Any idea how this can be achieved? How can I pass the value to the parent object?

3
  • 2
    Why do you have a return statement? It's halting your loop after the first number is found. Simply remove it and use an else if you don't want a recursive call to happen. Commented Dec 16, 2015 at 15:33
  • OK. I'll try. I just edited my question to make it a bit more clear. Commented Dec 16, 2015 at 15:39
  • Thanks. That helped. Commented Dec 16, 2015 at 15:54

1 Answer 1

2

The problem is that "return;" That returns from the function, thereby only leaving the first item changed. Here's a fiddle:

https://jsfiddle.net/mckinleymedia/rbf26hcw/

function resetCounts(obj) {
  for (var el in obj) {
    if (obj.hasOwnProperty(el)) {
      if (typeof obj[el] == 'number') {
        if (obj[el] > 0) {
          obj[el] = 0;
        }
      }
      obj[el] = resetCounts(obj[el]);
    }
  }
  return obj;
};
var counts = { '0': 6, '15': 3, '35': 5, '55': 3, '75': 85 };
console.log(counts);
counts = resetCounts(counts);
console.log(counts);

So you know, using lodash, if you've just got counts in there AND you're not having to reset deep numbers, you could reset each tag with just this:

_.each(counts, function(v,k){ counts[k] = 0; });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. Works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.