如何遍历以对象为成员的纯JavaScript对象?

JavaScript

乐泡芙

2020-03-09

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

第248篇《如何遍历以对象为成员的纯JavaScript对象?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
L前端 2020.03.09

The solution that work for me is the following

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

var obj={
name:"SanD",
age:"27"
}
Object.keys(obj).forEach((key)=>console.log(key,obj[key]));

To loop through JavaScript Object we can use forEach and to optimize code we can use arrow function

达蒙小胖 2020.03.09

Another option:

var testObj = {test: true, test1: false};
for(let x of Object.keys(testObj)){
    console.log(x);
}
米亚西里 2020.03.09

ECMAScript-2017, just finalized a month ago, introduces Object.values(). So now you can do this:

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

In ES7 you can do:

for (const [key, value] of Object.entries(obj)) {
  //
}
樱凯 2020.03.09
for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}
AMandy 2020.03.09

Using Underscore.js’s _.each:

_.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
        console.log(value);
    });
});
神乐路易 2020.03.09

在ECMAScript 5下,您可以将Object.keys()结合使用Array.prototype.forEach()

var obj = {
  first: "John",
  last: "Doe"
};

//
//	Visit non-inherited enumerable keys
//
Object.keys(obj).forEach(function(key) {

  console.log(key, obj[key]);

});

L十三 2020.03.09

In ES6/2015 you can loop through an object like this: (using arrow function)

Object.keys(myObj).forEach(key => {
  console.log(key);        // the name of the current key.
  console.log(myObj[key]); // the value of the current key.
});

jsbin

In ES7/2016 you can use Object.entries instead of Object.keys and loop through an object like this:

Object.entries(myObj).forEach(([key, val]) => {
  console.log(key); // the name of the current key.
  console.log(val); // the value of the current key.
});

The above would also work as a one-liner:

Object.entries(myObj).forEach(([key, val]) => console.log(key, val));

jsbin

In case you want to loop through nested objects as well, you can use a recursive function (ES6):

const loopNestedObj = obj => {
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
    else console.log(key, obj[key]); // or do something with key and val.
  });
};

jsbin

Same as function above, but with ES7 Object.entries() instead of Object.keys():

const loopNestedObj = obj => {
  Object.entries(obj).forEach(([key, val]) => {
    if (val && typeof val === "object") loopNestedObj(val); // recurse.
    else console.log(key, val); // or do something with key and val.
  });
};

Here we loop through nested objects change values and return a new object in one go using Object.entries() combined with Object.fromEntries() (ES10/2019):

const loopNestedObj = obj =>
  Object.fromEntries(
    Object.entries(obj).map(([key, val]) => {
      if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
      else [key, updateMyVal(val)]; // or do something with key and val.
    })
  );
JinJinPro 2020.03.09
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]);
    }
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android