在JavaScript中迭代对象,保持父母

我正在与一个迭代函数战斗。 我有这个对象

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

我不知道该去哪里 我必须改变对象吗?

提前致谢

       

网上收集的解决方案 "在JavaScript中迭代对象,保持父母"

这是解决scheme:

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