Thursday, 17 January 2019

angularjs - Best practice looping through a JavaScript object





I have the following JavaScript object which I need to apply parseFloat to any number value field (in order for ngTable to sort correctly).



I'm having a tough time looping through the Object to do this. I've tried a nested angular.forEach, but I have scoping issues (inner loops don't see outer variables).




What's the best manner to approach this?



The Object names (i.e: Person and PersonDetails) are dynamic. :/



My object:



{
"data": [
{
"Person": {

"id" : "1",
"age": "23",
"days": "5",
"first_name": "Joe",
"last_name": "Smith",
},
"PersonDetails": {
"id": "4",
"name": "Cousin",
"oldest: "2",

}
},
{
"Person": {
"id" : "2",
"age": "18",
"days": "3",
"first_name": "John",
"last_name": "Doe",
},

"PersonDetails": {
"id": "4",
"name": "Second Cousin",
"oldest: "3",
}
}
...
...
]
};


Answer



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}]}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...