循环遍历javascript对象的最佳实践

wiz*_*fza 40 javascript angularjs

我有以下JS对象,我需要将parseFloat应用于任何数字值字段(以便ngTable正确排序).

我正在通过Object循环执行此操作.我已经尝试过嵌套的angular.forEach但是我遇到了范围问题(内部循环没有看到外部变量).

接近这个的最佳方式是什么?

编辑:应该提到对象名称(即:Person,PersonDetails)是动态的.:/

我的目标:

{
    "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",
            }
        }
        ...
        ...
    ]
};
Run Code Online (Sandbox Code Playgroud)

Pau*_* S. 13

你可以做这样的测试

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
Run Code Online (Sandbox Code Playgroud)

并且递归所有节点,例如,矫枉过正

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}]}
Run Code Online (Sandbox Code Playgroud)