我正在与迭代功能作斗争。我有这个对象:
var table = {
"general": {
"amount": ["mandatory", "isAmount"],
"order_id": ["mandatory", "isString"]
},
"card": {
"number": ["Regex:/^[0-9]{16}$/", "mandatory"],
"expiry": {
"month": ["Regex:/^[0-9]{2}$", "mandatory"],
"year": ["Regex:/^[0-9]{4}$/", "mandatory"]
},
"network": ["List:maestro|visa|mastercard|amex|jcb", "mandatory"],
"cvv": ["Regex:/^[0-9]{3,4}$/", "mandatory"]
}
}
这里的目标是console.log
这个:
general.amount : ["mandatory", "isAmount"]
general.order_id: ["mandatory", "isString"]
card.number: ["Regex:/^[0-9]{16}$/", "mandatory"]
card.expiry.month: ["Regex:/^[0-9]{2}$", "mandatory"]
card.expiry.year: ["Regex:/^[0-9]{4}$/", "mandatory"]
card.network: ["List:maestro|visa|mastercard|amex|jcb", "mandatory"]
card.cvv: ["Regex:/^[0-9]{3,4}$/", "mandatory"]
- >保持每个领域的父母,并展示他们。
实际上,我已经尝试了很多东西,这是开始:
function boucle(object, parent) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
var value = object[key];
if (value.length) {
console.log(parent + '.' + key);
} else {
if (parent) {
parent += "."+key;
} else {
parent = key;
}
boucle(value, parent)
}
}
}
}
我不知道该去哪儿。我必须更换物体吗?
提前致谢
答案 0 :(得分:2)
以下是解决方案:
function boucle(obj, parent) {
for (var i in obj) {
var parent1 = (parent ? parent + '.' : '') + i;
if (obj.hasOwnProperty(i)) {
if (obj[i].length) {
console.log(parent1);
} else {
boucle(obj[i], parent1);
}
}
}
}
答案 1 :(得分:0)
Use this.
$.each(table,function(key1){
$.each(table[key1],function(key2){
if(table[key1][key2] instanceof Array){
console.log(key1+'.'+key2+' :'+table[key1][key2][0]+','+table[key1][key2][1]);
}else{
$.each(table[key1][key2],function(key3){
console.log(key1+'.'+key2+'.'+key3+ ' :'+table[key1][key2][key3][0]+','+table[key1][key2][key3][1]);
})
}
})
})