문제

That's my javascript object.

var myobj = {
'arr1': ['abc','dsf2','ss4'],
'arr893f': ['839f','mdo9','ks92','kcm8'],
 ....
}

How to walk through all the values of arrays that are inside of this object? I.e. I need to walk through 'abc','dsf2','ss4', '839f','mdo9','ks92', ...

I can walk through

for (var value in myobj ) {
  console.log(value);//arr1, arr893f
}

but that's still not what I need. I need to get 'abc','dsf2','ss4', '839f','mdo9','ks92', ... into the console by walking through the object.

P.S. Only structure of this object is known. We don't know the key names or values.

Thank you.

도움이 되었습니까?

해결책

for(var propName in myobj)
{
    if(myobj.hasOwnProperty(propName)){
        var item = myobj[propName];
        if(item instanceof Array)
        {
            item.forEach(function(arrItem, index){
                //woo!
            });
        }
    }
}

I thought it might be useful to create a convenience method on the Object.prototype:

(function(){
    function enumerateProperties(cbHandler, ownProperty){
        ownProperty = typeof(ownProperty) == "boolean" ? ownProperty : true;
        if(typeof(cbHandler) != "function"){
            throw new Error("invalid callback");
        }
        for(var propName in this){
            if((!ownProperty) || this.hasOwnProperty(propName)){
                cbHandler(propName, this[propName]);            
            }
        }
    }
    Object.prototype["enumerateProperties"] =
          Object.prototype["enumerateProperties"] || enumerateProperties;
})();

so now you can:

var o = {a:1, b:[1, 2, 3], c:3};

o.enumerateProperties(function(propName,propValue){
    console.log(propName);
    if(propValue instanceof Array){
        console.log(propValue.join(", "));
    }
    else{
        console.log(propValue);
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top