如何循环遍历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"
    }
}

当前回答

适合我的解决方案如下:

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

其他回答

var validation_messages = {
    "key_1": {
        "your_name": "jimmy",
        "your_msg": "hello world"
    },
    "key_2": {
        "your_name": "billy",
        "your_msg": "foo equals bar"
    }
}
for (var i in validation_messages) {
    console.log("i = \"" + i + "\"");
    console.log("validation_messages[\"" + i + "\"] = ");
    console.log(validation_messages[i]);
    console.log("\n");
    for (var j in validation_messages[i]) {
        console.log("j = \"" + j + "\"");
        console.log("validation_messages[\"" + i + "\"][\"" + j + "\"] = \"" + validation_messages[i][j] + "\"");
        console.log("\n");
    }
    console.log('\n');
}

输出:

i = "key_1"
validation_messages["key_1"] = 
{
  your_name:"jimmy",
  your_msg:"hello world"
}

j = "your_name"
validation_messages["key_1"]["your_name"] = "jimmy"

j = "your_msg"
validation_messages["key_1"]["your_msg"] = "hello world"


i = "key_2"
validation_messages["key_2"] = 
{
  your_name:"billy",
  your_msg:"foo equals bar"
}

j = "your_name"
validation_messages["key_2"]["your_name"] = "billy"

j = "your_msg"
validation_messages["key_2"]["your_msg"] = "foo equals bar"

异国情调的单深度穿越

JSON.stringify(validation_messages,(field,value)=>{
  if(!field) return value;

  // ... your code

  return value;
})

在这个解决方案中,我们使用了替换器,它允许深入遍历整个对象和嵌套对象-在每个级别上,您将获得所有字段和值。如果您需要获取每个字段的完整路径,请查看此处。

var验证消息={“key_1”:{“your_name”:“jimmy”,“your_msg”:“hello world”},“key_2”:{“your_name”:“billy”,“your_msg”:“foo等于bar”,“深”:{“颜色”:“红色”,“大小”:“10px”}}}JSON.stringify(validation_messages,(字段,值)=>{if(!field)返回值;console.log(`key:${field.padEnd(11)}-value:${value}`);返回值;})

for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}

变量obj={name:“SanD”,年龄:“27”}Object.keys(obj).forEach((key)=>console.log(key,obj[key]));

为了循环遍历JavaScript对象,我们可以使用forEach,为了优化代码,可以使用箭头函数。

使用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>