Best practice looping through a JavaScript object [duplicate]
You can do a test like this:
function representsNumber(str) {
return str === (+str).toString();
}
// E.g. usage
representsNumber('a'); // false
representsNumber([]); // false
representsNumber(1); // false (it IS a number)
representsNumber('1.5'); // true
representsNumber('-5.1'); // true
representsNumber('NaN'); // true
And recurse over all your nodes. Overkill example:
function seeker(o, test, _true, _false) {
_true || (_true = function (e) {return e;});
_false || (_false = function (e) {return e;});
function recursor(o) {
var k;
if (o instanceof Array)
for (k = 0; k < o.length; ++k) // Iterate over an array
if (typeof o[k] !== 'object')
o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
else
recursor(o[k]);
else
for (k in o) // Iterate over an object
if (typeof o[k] !== 'object')
o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
else
recursor(o[k]);
}
if (typeof o === "object")
return recursor(o), o;
else
return test(o) ? _true(o) : _false(o); // Not an object, just transform
}
// Sample usage
seeker({foo: [{bar: "20"}]}, representsNumber, parseFloat);
// {foo: [{bar: 20}]}