开发者

How to operate object structure in JavaScript

开发者 https://www.devze.com 2023-02-07 22:37 出处:网络
var obj = { skill:{ eat:true, walk:true }, address:{ home:\"where\", company:\"where\" } }; I can get one item by:
var obj = {
   skill:{
      eat:true,
      walk:true
   },
   address:{
      home:"where",
      company:"where"
   }
};

I can get one item by:

tes开发者_如何转开发ter.activate(obj[skill]);

How can I get all the items?


You can iterate through the properties of an object with 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. 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) )


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

0

精彩评论

暂无评论...
验证码 换一张
取 消