如何将对象作为成员循环遍历纯JavaScript对象?

时间:2022-10-30 10:28:45

How can I loop through all members in a JavaScript object including values that are objects.

如何循环遍历JavaScript对象中的所有成员,包括作为对象的值。

For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?

例如,如何对其进行循环(分别访问“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"
    }
}

17 个解决方案

#1


1780  

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

#2


546  

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

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

});

#3


360  

The problem with this

这里的问题

for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

is that you’ll also loop through the primitive object's prototype.

您还将循环遍历原始对象的原型。

With this one you will avoid it:

有了这个,你将避免它:

for (var key in validation_messages) {
   if (validation_messages.hasOwnProperty(key)) {
      var obj = validation_messages[key];
      for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
            alert(prop + " = " + obj[prop]);
         }
      }
   }
}

#4


132  

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

在ES6中,您可以通过如下对象进行循环:(使用箭头函数)

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

jsbin

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

在ES7中可以使用Object。条目,而不是对象。通过如下对象进行键和循环:

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.keys(myObj).forEach(key => console.log(key, myObj[key]));

jsbin

jsbin

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

如果您也想循环遍历嵌套对象,可以使用递归函数(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

jsbin

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

与上面的函数相同,但是使用ES7对象。条目,而不是种:

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

If you are into functional programming you can use Object.keys/Object.entries to enumerate the object, then process the values and then use reduce() to convert back to a new object.

如果您喜欢函数式编程,可以使用Object.keys/Object。枚举对象的条目,然后处理值,然后使用reduce()将其转换回新的对象。

const loopNestedObj = (obj) => 
  Object.keys(obj)
    // Use .filter(), .map(), etc. if you need.
    .reduce((newObj, key) => 
      (obj[key] && typeof obj[key] === 'object') ?
        {...newObj, [key]: loopNestedObj(obj[key])} :  // recurse.
        {...newObj, [key]: obj[key]},                  // Define value.
      {});

#5


91  

Using Underscore.js’s _.each:

使用下划线。js _.each:

_.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
        console.log(value);
    });
});

#6


51  

If you use recursion you can return object properties of any depth-

如果使用递归,则可以返回任何深度的对象属性。

function lookdeep(object){
    var collection= [], index= 0, next, item;
    for(item in object){
        if(object.hasOwnProperty(item)){
            next= object[item];
            if(typeof next== 'object' && next!= null){
                collection[index++]= item +
                ':{ '+ lookdeep(next).join(', ')+'}';
            }
            else collection[index++]= [item+':'+String(next)];
        }
    }
    return collection;
}

//example

var O={
    a:1, b:2, c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
};
var lookdeepSample= 'O={'+ lookdeep(O).join(',\n')+'}';


/*  returned value: (String)
O={
    a:1, 
    b:2, 
    c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
}

*/

#7


27  

I know it's waaay late, but it did take me 2 minutes to write this optimized and improved version of AgileJon's answer:

我知道已经很晚了,但是我花了2分钟来写这个优化和改进版本的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]);
            }

        }

    }

}

#8


26  

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

#9


8  

for(var key in validation_messages){
    for(var subkey in validation_messages[key]){
        //code here
        //subkey being value, key being 'yourname' / 'yourmsg'
    }
}

#10


8  

This answer is an aggregate of the solutions that were provided in this post with some performance feedbacks. I think there is 2 use-cases and the OP didn't mention if he needs to access the keys in order use them during the loop process.

这个答案是本文提供的解决方案的集合,并提供了一些性能反馈。我认为有两个用例,OP没有提到他是否需要访问键以便在循环过程中使用它们。

I. the keys need to be accessed,

✔ the of and Object.keys approach

✔和对象。键的方法

let k;
for (k of Object.keys(obj)) {

    /*        k : key
     *   obj[k] : value
     */
}

✔ the in approach

✔的方法

let k;
for (k in obj) {

    /*        k : key
     *   obj[k] : value
     */
}

Use this one with cautious, as it could print prototype'd properties of obj

小心使用这个,因为它可以打印obj的原型属性

✔ the ES7 approach

✔ES7方法

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

}

However, at the time of the edit I wouldn't recommend the ES7 method, because JavaScript initializes a lot of variables internally to build this procedure (see the feedbacks for proof). Unless you are not developing a huge app which deserves optimization, then it is ok but if optimization is your priority you should think about it.

但是,在编辑时,我不建议使用ES7方法,因为JavaScript在内部初始化了许多变量来构建这个过程(参见反馈以获得证据)。除非你正在开发一个值得优化的大型应用程序,否则这是可以的,但是如果优化是你的首要任务,你应该考虑它。

II. we just need to access each values,

✔ the of and Object.values approach

✔和对象。值的方法

let v;
for (v of Object.values(obj)) {

}

More feedbacks about the tests :

  • Caching Object.keys or Object.values performance is negligible
  • 缓存对象。键或对象。值的性能是可以忽略的

For instance,

例如,

const keys = Object.keys(obj);
let i;
for (i of keys) {
  //
}
// same as
for (i of Object.keys(obj)) {
  //
}
  • For Object.values case, using a native for loop with cached variables in Firefox seems to be a little faster than using a for...of loop. However the difference is not that important and Chrome is running for...of faster than native for loop, so I would recommend to use for...of when dealing with Object.values in any cases (4th and 6th tests).

    为对象。值的情况是,在Firefox中使用带有缓存变量的本机for循环似乎比使用for循环要快一些。的循环。但是区别并不重要,Chrome是为了……循环的速度比本机快,所以我建议使用for…在处理对象时。任何情况下的值(第4和第6个测试)。

  • In Firefox, the for...in loop is really slow, so when we want to cache the key during the iteration it is better to use Object.keys. Plus Chrome is running both structure at equal speed (1st and last tests).

    在Firefox中,……在循环中确实很慢,所以当我们想在迭代期间缓存密钥时,最好使用Object.keys。此外,Chrome的两种结构运行速度都是一样的(第一次和最后一次测试)。

You can check the tests here : https://jsperf.com/es7-and-misc-loops

您可以在这里检查测试:https://jsperf.com/es7and -misc-loop

#11


5  

Here comes the improved and recursive version of AgileJon's solution (demo):

这里是AgileJon的解决方案(demo)的改进和递归版本:

function loopThrough(obj){
  for(var key in obj){
    // skip loop if the property is from prototype
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      //your code
      console.log(key+" = "+obj[key]);
    } else {
      loopThrough(obj[key]);
    }
  }
}
loopThrough(validation_messages);

This solution works for all kinds of different depths.

这个解决方案适用于各种不同的深度。

#12


5  

In ES7 you can do:

在ES7中你可以做到:

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

#13


4  

Another option:

另一个选择:

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

#14


3  

I think it's worth pointing out that jQuery sorts this out nicely with $.each().

我认为值得指出的是,jQuery用$.each()很好地解决了这个问题。

See: https://api.jquery.com/each/

参见:https://api.jquery.com/each/

For example:

例如:

$('.foo').each(function() {
    console.log($(this));
});

$(this) being the single item inside the object. Swap $('.foo') to a variable if you don't want to use jQuery's selector engine.

$(this)是对象内的单个项。如果不想使用jQuery的选择器引擎,将$('.foo')转换为变量。

#15


3  

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

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

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

#16


2  

I couldn't get the above posts to do quite what I was after.

我无法得到上面的帖子来做我想做的事情。

After playing around with the other replies here, I made this. It's hacky, but it works!

在这里和其他回复一起玩了一会儿之后,我做了这个。这是陈词滥调,但确实有效!

For this object:

这个对象:

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

... this code:

…这段代码:

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

... produces this in the console:

…在控制台中产生:

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

#17


-5  

In my case (on the basis of the preceding) is possible any number of levels.

在我的例子中(在前面的基础上)是可能的任何数量的级别。

var myObj = {
    rrr: undefined,
    pageURL    : "BLAH",
    emailBox   : {model:"emailAddress", selector:"#emailAddress"},
    passwordBox: {model:"password"    , selector:"#password"},
    proba: {odin:{dva:"rr",trr:"tyuuu"}, od:{ff:5,ppa:{ooo:{lll:'lll'}},tyt:'12345'}}
};


function lookdeep(obj,p_Name,gg){
    var A=[], tem, wrem=[], dd=gg?wrem:A;
    for(var p in obj){
        var y1=gg?'':p_Name, y1=y1 + '.' + p;
        if(obj.hasOwnProperty(p)){
           var tem=obj[p];
           if(tem && typeof tem=='object'){
               a1=arguments.callee(tem,p_Name,true);
               if(a1 && typeof a1=='object'){for(i in a1){dd.push(y1 + a1[i])};}
            }
            else{
               dd.push(y1 + ':' + String(tem));
            }
        }
    };
    return dd
};


var s=lookdeep(myObj,'myObj',false);
for (var x=0; x < s.length; ++x) {
console.log(s[x]+'\n');}

result:

结果:

["myObj.rrr:undefined",
"myObj.pageURL:BLAH",
"myObj.emailBox.model:emailAddress",
"myObj.emailBox.selector:#emailAddress",
"myObj.passwordBox.model:password",
"myObj.passwordBox.selector:#password",
"myObj.proba.odin.dva:rr",
"myObj.proba.odin.trr:tyuuu",
"myObj.proba.od.ff:5",
"myObj.proba.od.ppa.ooo.lll:lll",
"myObj.proba.od.tyt:12345"]

#1


1780  

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

#2


546  

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

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

});

#3


360  

The problem with this

这里的问题

for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

is that you’ll also loop through the primitive object's prototype.

您还将循环遍历原始对象的原型。

With this one you will avoid it:

有了这个,你将避免它:

for (var key in validation_messages) {
   if (validation_messages.hasOwnProperty(key)) {
      var obj = validation_messages[key];
      for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
            alert(prop + " = " + obj[prop]);
         }
      }
   }
}

#4


132  

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

在ES6中,您可以通过如下对象进行循环:(使用箭头函数)

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

jsbin

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

在ES7中可以使用Object。条目,而不是对象。通过如下对象进行键和循环:

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.keys(myObj).forEach(key => console.log(key, myObj[key]));

jsbin

jsbin

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

如果您也想循环遍历嵌套对象,可以使用递归函数(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

jsbin

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

与上面的函数相同,但是使用ES7对象。条目,而不是种:

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

If you are into functional programming you can use Object.keys/Object.entries to enumerate the object, then process the values and then use reduce() to convert back to a new object.

如果您喜欢函数式编程,可以使用Object.keys/Object。枚举对象的条目,然后处理值,然后使用reduce()将其转换回新的对象。

const loopNestedObj = (obj) => 
  Object.keys(obj)
    // Use .filter(), .map(), etc. if you need.
    .reduce((newObj, key) => 
      (obj[key] && typeof obj[key] === 'object') ?
        {...newObj, [key]: loopNestedObj(obj[key])} :  // recurse.
        {...newObj, [key]: obj[key]},                  // Define value.
      {});

#5


91  

Using Underscore.js’s _.each:

使用下划线。js _.each:

_.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
        console.log(value);
    });
});

#6


51  

If you use recursion you can return object properties of any depth-

如果使用递归,则可以返回任何深度的对象属性。

function lookdeep(object){
    var collection= [], index= 0, next, item;
    for(item in object){
        if(object.hasOwnProperty(item)){
            next= object[item];
            if(typeof next== 'object' && next!= null){
                collection[index++]= item +
                ':{ '+ lookdeep(next).join(', ')+'}';
            }
            else collection[index++]= [item+':'+String(next)];
        }
    }
    return collection;
}

//example

var O={
    a:1, b:2, c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
};
var lookdeepSample= 'O={'+ lookdeep(O).join(',\n')+'}';


/*  returned value: (String)
O={
    a:1, 
    b:2, 
    c:{
        c1:3, c2:4, c3:{
            t:true, f:false
        }
    },
    d:11
}

*/

#7


27  

I know it's waaay late, but it did take me 2 minutes to write this optimized and improved version of AgileJon's answer:

我知道已经很晚了,但是我花了2分钟来写这个优化和改进版本的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]);
            }

        }

    }

}

#8


26  

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

#9


8  

for(var key in validation_messages){
    for(var subkey in validation_messages[key]){
        //code here
        //subkey being value, key being 'yourname' / 'yourmsg'
    }
}

#10


8  

This answer is an aggregate of the solutions that were provided in this post with some performance feedbacks. I think there is 2 use-cases and the OP didn't mention if he needs to access the keys in order use them during the loop process.

这个答案是本文提供的解决方案的集合,并提供了一些性能反馈。我认为有两个用例,OP没有提到他是否需要访问键以便在循环过程中使用它们。

I. the keys need to be accessed,

✔ the of and Object.keys approach

✔和对象。键的方法

let k;
for (k of Object.keys(obj)) {

    /*        k : key
     *   obj[k] : value
     */
}

✔ the in approach

✔的方法

let k;
for (k in obj) {

    /*        k : key
     *   obj[k] : value
     */
}

Use this one with cautious, as it could print prototype'd properties of obj

小心使用这个,因为它可以打印obj的原型属性

✔ the ES7 approach

✔ES7方法

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

}

However, at the time of the edit I wouldn't recommend the ES7 method, because JavaScript initializes a lot of variables internally to build this procedure (see the feedbacks for proof). Unless you are not developing a huge app which deserves optimization, then it is ok but if optimization is your priority you should think about it.

但是,在编辑时,我不建议使用ES7方法,因为JavaScript在内部初始化了许多变量来构建这个过程(参见反馈以获得证据)。除非你正在开发一个值得优化的大型应用程序,否则这是可以的,但是如果优化是你的首要任务,你应该考虑它。

II. we just need to access each values,

✔ the of and Object.values approach

✔和对象。值的方法

let v;
for (v of Object.values(obj)) {

}

More feedbacks about the tests :

  • Caching Object.keys or Object.values performance is negligible
  • 缓存对象。键或对象。值的性能是可以忽略的

For instance,

例如,

const keys = Object.keys(obj);
let i;
for (i of keys) {
  //
}
// same as
for (i of Object.keys(obj)) {
  //
}
  • For Object.values case, using a native for loop with cached variables in Firefox seems to be a little faster than using a for...of loop. However the difference is not that important and Chrome is running for...of faster than native for loop, so I would recommend to use for...of when dealing with Object.values in any cases (4th and 6th tests).

    为对象。值的情况是,在Firefox中使用带有缓存变量的本机for循环似乎比使用for循环要快一些。的循环。但是区别并不重要,Chrome是为了……循环的速度比本机快,所以我建议使用for…在处理对象时。任何情况下的值(第4和第6个测试)。

  • In Firefox, the for...in loop is really slow, so when we want to cache the key during the iteration it is better to use Object.keys. Plus Chrome is running both structure at equal speed (1st and last tests).

    在Firefox中,……在循环中确实很慢,所以当我们想在迭代期间缓存密钥时,最好使用Object.keys。此外,Chrome的两种结构运行速度都是一样的(第一次和最后一次测试)。

You can check the tests here : https://jsperf.com/es7-and-misc-loops

您可以在这里检查测试:https://jsperf.com/es7and -misc-loop

#11


5  

Here comes the improved and recursive version of AgileJon's solution (demo):

这里是AgileJon的解决方案(demo)的改进和递归版本:

function loopThrough(obj){
  for(var key in obj){
    // skip loop if the property is from prototype
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      //your code
      console.log(key+" = "+obj[key]);
    } else {
      loopThrough(obj[key]);
    }
  }
}
loopThrough(validation_messages);

This solution works for all kinds of different depths.

这个解决方案适用于各种不同的深度。

#12


5  

In ES7 you can do:

在ES7中你可以做到:

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

#13


4  

Another option:

另一个选择:

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

#14


3  

I think it's worth pointing out that jQuery sorts this out nicely with $.each().

我认为值得指出的是,jQuery用$.each()很好地解决了这个问题。

See: https://api.jquery.com/each/

参见:https://api.jquery.com/each/

For example:

例如:

$('.foo').each(function() {
    console.log($(this));
});

$(this) being the single item inside the object. Swap $('.foo') to a variable if you don't want to use jQuery's selector engine.

$(this)是对象内的单个项。如果不想使用jQuery的选择器引擎,将$('.foo')转换为变量。

#15


3  

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

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

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

#16


2  

I couldn't get the above posts to do quite what I was after.

我无法得到上面的帖子来做我想做的事情。

After playing around with the other replies here, I made this. It's hacky, but it works!

在这里和其他回复一起玩了一会儿之后,我做了这个。这是陈词滥调,但确实有效!

For this object:

这个对象:

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

... this code:

…这段代码:

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

... produces this in the console:

…在控制台中产生:

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

#17


-5  

In my case (on the basis of the preceding) is possible any number of levels.

在我的例子中(在前面的基础上)是可能的任何数量的级别。

var myObj = {
    rrr: undefined,
    pageURL    : "BLAH",
    emailBox   : {model:"emailAddress", selector:"#emailAddress"},
    passwordBox: {model:"password"    , selector:"#password"},
    proba: {odin:{dva:"rr",trr:"tyuuu"}, od:{ff:5,ppa:{ooo:{lll:'lll'}},tyt:'12345'}}
};


function lookdeep(obj,p_Name,gg){
    var A=[], tem, wrem=[], dd=gg?wrem:A;
    for(var p in obj){
        var y1=gg?'':p_Name, y1=y1 + '.' + p;
        if(obj.hasOwnProperty(p)){
           var tem=obj[p];
           if(tem && typeof tem=='object'){
               a1=arguments.callee(tem,p_Name,true);
               if(a1 && typeof a1=='object'){for(i in a1){dd.push(y1 + a1[i])};}
            }
            else{
               dd.push(y1 + ':' + String(tem));
            }
        }
    };
    return dd
};


var s=lookdeep(myObj,'myObj',false);
for (var x=0; x < s.length; ++x) {
console.log(s[x]+'\n');}

result:

结果:

["myObj.rrr:undefined",
"myObj.pageURL:BLAH",
"myObj.emailBox.model:emailAddress",
"myObj.emailBox.selector:#emailAddress",
"myObj.passwordBox.model:password",
"myObj.passwordBox.selector:#password",
"myObj.proba.odin.dva:rr",
"myObj.proba.odin.trr:tyuuu",
"myObj.proba.od.ff:5",
"myObj.proba.od.ppa.ooo.lll:lll",
"myObj.proba.od.tyt:12345"]