最佳实践循环通过JavaScript对象

前端之家收集整理的这篇文章主要介绍了最佳实践循环通过JavaScript对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Access / process (nested) objects,arrays or JSON12个
> For-each over an array in JavaScript?20个
我有以下JS对象,我需要将parseFloat应用于任何数字值字段(以使ngTable正确排序).

我有一个困难的时间循环通过对象来做到这一点.我已经尝试嵌套angular.forEach但是有范围问题(内部循环看不到外部变量).

最好的方法是什么?

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

我的对象:

@H_404_12@{ "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","name": "Second Cousing","oldest: "3",} } ... ... ] };

解决方法

你可以这样做一个测试 @H_404_12@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

并递归所有的节点,过度的例子

@H_404_12@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 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 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 } // e.g. usage seeker({foo: [{bar: "20"}]},representsNumber,parseFloat); // {foo: [{bar: 20}]}
原文链接:https://www.f2er.com/js/155166.html

猜你在找的JavaScript相关文章