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

其他回答

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

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

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

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

有几种方法可以做到这一点。。。

1) 两层的。。。循环中。。。

for (let key in validation_messages) {
   const vmKeys = validation_messages[key];
   for (let vmKey in vmKeys) {
      console.log(vmKey + vmKeys[vmKey]);
   }
}

2) 使用Object.key

Object.keys(validation_messages).forEach(key => {
   const vmKeys = validation_messages[key];
   Object.keys(vmKeys).forEach(key => {
    console.log(vmKeys + vmKeys[key]);
   });
});

3) 递归函数

const recursiveObj = obj => {
  for(let key in obj){
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      console.log(key + obj[key]);
    } else {
      recursiveObj(obj[key]);
    }
  }
}

并将其称为:

recursiveObj(validation_messages);