简体   繁体   English

如何在JavaScript中操作对象结构

[英]How to operate object structure in JavaScript

var obj = {
   skill:{
      eat:true,
      walk:true
   },
   address:{
      home:"where",
      company:"where"
   }
};

I can get one item by: 我可以通过以下方式获得一件:

tester.activate(obj[skill]);

How can I get all the items? 如何获得所有物品?

You can iterate through the properties of an object with for ... in : 您可以在中使用for ... in遍历对象的属性:

for (var k in obj) {
  if (obj.hasOwnProperty(k)) {
    var value = obj[k];
    alert("property name is " + k + " value is " + value);
  }
}

The call to the "hasOwnProperty" function is there to keep this code from iterating through properties present on "obj" that are actually inherited from the Object prototype. 那里有对“ hasOwnProperty”函数的调用,以防止该代码重复访问实际上从Object原型继承的“ obj”上存在的属性。 Sometimes you might want to include those, but in this case it's safe to filter them out (I think). 有时您可能希望将它们包括在内,但是在这种情况下,将它们过滤掉是安全的(我认为)。 (And @sdleihssirhc points out that if you want to be really sure, you can use Object.prototype.hasOwnProperty.call(obj, k) ) (@sdleihssirhc指出,如果您确实要确定,可以使用Object.prototype.hasOwnProperty.call(obj, k)

If you need the skill you can get 如果您需要技能,可以得到

obj.skill

If you need the address you can get 如果您需要地址,您可以得到

obj.address

or if you wanted to get the individual data: 或者,如果您想获取单个数据:

var eat = obj.skill.eat;
var company = obj.address.company;

If you want all the items you can iterate over the structure and push all the items to an array 如果需要所有项目,则可以遍历结构并将所有项目推入数组

function pushObjToArray(obj, array) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
             if (obj[key] instanceof Array) {
                  pushObjToArray(obj[key], array);
             } else if (obj[key] instanceof Object) {
                  pushObjToArray(obj[key], array);
             } else {
                  array.push(obj[key]);
             }
        }
    }
    return array;
}

var array = [];
pushObjToArray(array, obj);

On second thought destroying the keys and pushing all data to an array is pretty useless. 第二个想法就是销毁密钥并将所有数据推入数组是毫无用处的。

What do you actaully want to do? 你实际想做什么?

You might be looking for something like _.flatten 您可能正在寻找类似_.flatten东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM