简体   繁体   中英

How to change an object's property from function

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?

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; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM