Comment boucler un objet JavaScript avec les objets en tant que membres

Mots clés : javascriptloopsjavascript

meilleur 5 Réponses Comment boucler un objet JavaScript avec les objets en tant que membres

vote vote

96

for (var key in validation_messages) {     // skip loop if the property is from prototype     if (!validation_messages.hasOwnProperty(key)) continue;      var obj = validation_messages[key];     for (var prop in obj) {         // skip loop if the property is from prototype         if (!obj.hasOwnProperty(prop)) continue;          // your code         alert(prop + " = " + obj[prop]);     } } 
vote vote

80

var obj = {    first: "John",    last: "Doe"  };    //  //	Visit non-inherited enumerable keys  //  Object.keys(obj).forEach(function(key) {      console.log(key, obj[key]);    });
vote vote

71

Object.keys(myObj).forEach(key => {   console.log(key);        // the name of the current key.   console.log(myObj[key]); // the value of the current key. }); 
Object.entries(myObj).forEach(([key, val]) => {   console.log(key); // the name of the current key.   console.log(val); // the value of the current key. }); 
Object.entries(myObj).forEach(([key, val]) => console.log(key, val)); 
const loopNestedObj = obj => {   Object.keys(obj).forEach(key => {     if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.     else console.log(key, obj[key]); // or do something with key and val.   }); }; 
const loopNestedObj = obj => {   Object.entries(obj).forEach(([key, val]) => {     if (val && typeof val === "object") loopNestedObj(val); // recurse.     else console.log(key, val); // or do something with key and val.   }); }; 
const loopNestedObj = obj =>   Object.fromEntries(     Object.entries(obj).map(([key, val]) => {       if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse       else [key, updateMyVal(val)]; // or do something with key and val.     })   ); 
vote vote

65

for (var key in validation_messages) {    var obj = validation_messages[key];    for (var prop in obj) {       alert(prop + " = " + obj[prop]);    } } 
for (var key in validation_messages) {    if (validation_messages.hasOwnProperty(key)) {       var obj = validation_messages[key];       for (var prop in obj) {          if (obj.hasOwnProperty(prop)) {             alert(prop + " = " + obj[prop]);          }       }    } } 
vote vote

52

_.each(validation_messages, function(value, key){     _.each(value, function(value, key){         console.log(value);     }); }); 

Questions similaires