如何循环遍历JavaScript对象中的所有成员,包括作为对象的值?

例如,我如何循环(分别访问“your_name”和“your_message”)?

var validation_messages = {
    "key_1": {
        "your_name": "jimmy",
        "your_msg": "hello world"
    },
    "key_2": {
        "your_name": "billy",
        "your_msg": "foo equals bar"
    }
}

当前回答

使用lodash_.forEach:

_.forEach({“a”:1,“b”:2},函数(值,键){console.log(键,值);});<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js“></script>

其他回答

p是值

for (var key in p) {
  alert(key + ' => ' + p[key]);
}

OR

Object.keys(p).forEach(key => { console.log(key, p[key]) })

这个问题

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

使用ES8Object.entries()应该是实现这一点的更紧凑的方法。

Object.entries(validation_messages).map(([key,object]) => {

    alert(`Looping through key : ${key}`);

    Object.entries(object).map(([token, value]) => {
        alert(`${token} : ${value}`);
    });
});

使用lodash_.forEach:

_.forEach({“a”:1,“b”:2},函数(值,键){console.log(键,值);});<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js“></script>

适合我的解决方案如下:

_private.convertParams = function(params){
    var params = [];
    Object.keys(values).forEach(function(key) {
        params.push({"id":key, "option":"Igual", "value":params[key].id})
    });
    return params;
}