在javascript中迭代javascript对象以获得正确的键

Iterating through a javascript object in javascript to get the correct key

本文关键字:javascript 迭代 对象      更新时间:2023-09-26

我有一个第三方函数返回一个对象

abc.xyz() --> this returns an object containing many objects,strings,boolean & arrays . Basically JSON style 
object. 

我正在遍历这个对象,只获取这个对象中的对象&该对象应该有一个名为"apple"的键。一旦我找到了那个对象,我就把键放入一个名为index的变量中;然后使用变量index来获取我想要的对象使用

abc.xyz()。index//理想情况下应该返回一个对象,但这是未定义的。为什么?

我的代码如下。

var pa= abc.xyz();
    var index; 
    for(var key in pa){
        if (pa.hasOwnProperty(key)) {
            var obj = pa[key];
            for(var prop in obj){
                if(obj.hasOwnProperty(prop)){
                    if(typeof obj === 'object'){ 
                        if( prop == "apple"){
                            index = key;
                        }
                    }
                }
            }
         }
    } 
    el.appendChild(ul(pa.index)); // though I get the correct index when i  
        console.log(index) but why is pa.index undefined? 

如果我不使用索引变量&我直接说爸。这里K是index的值,它是有效的。那为什么不及格呢?指数的工作吗?

下面的例子说明了javascript中两种不同的属性访问语法是如何工作的:

var o = {
  index: 'this is index',
  APPLE: 'this is APPLE'
};
var index = 'APPLE';
console.log(o.index);     // --> this is index
console.log(o[index]);    // --> this is APPLE  *
console.log(o['index']);  // --> this is index
在这种情况下,您应该使用标有*

。此形式查找o的属性,其名称与变量index中包含的匹配。另外两种形式只查找名为"index"的属性。所以你的例子的最后一行应该是:

el.appendChild(ul(pa[index]));   // assuming that `el` and `ul()` were both
                                 // defined appropriately elsewhere in your 
                                 // script.

也……看来你的逻辑可以大大简化了。考虑以下内容:

var pa = abc.xyz();
var result; 
for(var key in pa){
  if (pa.hasOwnProperty(key)) {
      var obj = pa[key];
      if(obj.hasOwnProperty("apple")) {
          result = obj;
      }
   }
}
el.appendChild(ul(result));

pa.index查找名为"index"的键

要查找index值的关键字,您需要使用pa[index] -没有句号,只有括号。