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

当前回答

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

其他回答

2020年,您需要不可变的通用函数

这将遍历由子对象、数组和字符串组成的多维对象,并应用自定义函数:

export const iterate = (object, func) => {
  const entries = Object.entries(object).map(([key, value]) =>
    Array.isArray(value)
      ? [key, value.map(e => iterate(e, func))]
      : typeof value === 'object'
      ? [key, iterate(value, func)]
      : [key, func(value)]
  );
  return Object.fromEntries(entries);
};

用法:

const r = iterate(data, e=>'converted_'+e);
console.log(r);

在ES7中,您可以执行以下操作:

for (const [key, value] of Object.entries(obj)) {
  //
}

一个月前刚刚完成的ECMAScript 2017引入了Object.values()。现在您可以这样做了:

let v;
for (v of Object.values(validation_messages))
   console.log(v.your_name);   // jimmy billy

AgileJon答案的优化和改进版本:

var key, obj, prop, owns = Object.prototype.hasOwnProperty;

for (key in validation_messages ) {

    if (owns.call(validation_messages, key)) {

        obj = validation_messages[key];

        for (prop in obj ) {

            // Using obj.hasOwnProperty might cause you headache if there is
            // obj.hasOwnProperty = function(){return false;}
            // but 'owns' will always work
            if (owns.call(obj, prop)) {
                console.log(prop, "=", obj[prop]);
            }
        }
    }
}

p是值

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

OR

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