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

当前回答

我无法得到之前的答案来做我想要的事情。

在玩弄了这里的其他回复之后,我做了这个。它很粗糙,但很管用!

对于此对象:

var myObj = {
    pageURL    : "BLAH",
    emailBox   : {model:"emailAddress", selector:"#emailAddress"},
    passwordBox: {model:"password"    , selector:"#password"}
};

…此代码:

// Get every value in the object into a separate array item ...
function buildArray(p_MainObj, p_Name) {
    var variableList = [];
    var thisVar = "";
    var thisYes = false;
    for (var key in p_MainObj) {
       thisVar = p_Name + "." + key;
       thisYes = false;
       if (p_MainObj.hasOwnProperty(key)) {
          var obj = p_MainObj[key];
          for (var prop in obj) {
            var myregex = /^[0-9]*$/;
            if (myregex.exec(prop) != prop) {
                thisYes = true;
                variableList.push({item:thisVar + "." + prop,value:obj[prop]});
            }
          }
          if ( ! thisYes )
            variableList.push({item:thisVar,value:obj});
       }
    }
    return variableList;
}

// Get the object items into a simple array ...
var objectItems = buildArray(myObj, "myObj");

// Now use them / test them etc... as you need to!
for (var x=0; x < objectItems.length; ++x) {
    console.log(objectItems[x].item + " = " + objectItems[x].value);
}

…在控制台中生成:

myObj.pageURL = BLAH
myObj.emailBox.model = emailAddress
myObj.emailBox.selector = #emailAddress
myObj.passwordBox.model = password
myObj.passwordBox.selector = #password

其他回答

异国情调的单深度穿越

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}`);返回值;})

适合我的解决方案如下:

_private.convertParams = function(params){
    var params = [];
    Object.keys(values).forEach(function(key) {
        params.push({"id":key, "option":"Igual", "value":params[key].id})
    });
    return params;
}
for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}
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]);
    }
}

p是值

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

OR

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