如何找出对象键是javascript中的字符串或数组

时间:2017-06-14 10:18:23

标签: javascript

这是我的JSON,现在我想找出属性是数组还是字符串。

{     “数据”:[

{ 

     "name": "my Service", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"

}, 

 { 
     "name": "my Service1", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
},

 { 

     "name": "my Service2", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
},

 { 

     "name": "my Service3", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
}

] }

现在如何找出属性是字符串还是数组。

2 个答案:

答案 0 :(得分:0)

检查字符串是:

Object.prototype.toString().call(var) === '[object Array]'

对数组的检查是:

{{1}}

答案 1 :(得分:0)

我理解你的答案,因为你需要识别每种房产类型。 我做了类似下面的代码。如果我不在您的路线,请告诉我。我只是安慰所有类型

var data = [

{ 

     "name": "my Service", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"

}, 

 { 
     "name": "my Service1", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
},

 { 

     "name": "my Service2", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
},

 { 

     "name": "my Service3", 
     "description":"   comes once here  " , 
     "tables":{ "tables":["rajaaaaa ","rajuuuuu","mommmm"]},
     "imgUrl":"../assets/images/nmpm.jpg"
}
];


data.forEach(obj=>{
 
   var keys = Object.keys(obj);
   for(var k=0;k< keys.length; k++){
      if(typeof obj[keys[k]] == 'string'){
           console.log(keys[k]+" is string");
      }else if(typeof obj[keys[k]] == 'object'){
          
           
            var obj_keys = Object.keys(obj[keys[k]]);
           
            for(var j = 0; j< obj_keys.length; j++){
            
           
             if(Object.prototype.toString.call( obj[keys[k]][obj_keys[j]] ) === '[object Array]') {
               console.log(keys[k]+" has Array");
             }
            }
           
      }
      
     
   }
 
});