Amin Uddin
Amin Uddin

Reputation: 1006

How to find a property type from javascript object?

How can I find out which property of an object is an Array type? Given the sample code below, I would expect to get the value OrderItemList.

function Order() {
    this.Id = 0;
    this.LocationID = 0;
    this.OrderItemList = new Array();      
}

var orderObject = new Order();

Upvotes: 0

Views: 125

Answers (1)

Vivek Pradhan
Vivek Pradhan

Reputation: 4857

From what I understand, you have an Object in javascript and you want to know if it contains an Array or not. If that's what you want to achieve you can simply traverse through all the keys for that object and check if the value is an instanceOf array.

In Jquery, you could do something like this (updated Demo):

$.each( orderObject, function( key, value ) {
if(value instanceof Array){
   console.log(key);
  }
});

Javascript equivalent:

for (var key in orderObject) {
 var val = orderObject[key];
  if (val instanceof Array){
   console.log(key);    
  }
}

I hope it gets you started in the right direction.

Edit - Like many have already pointed length attribute can not be used to uniquely distinguish an array from a string although you could do a typeof check to see if the value is a string.

Upvotes: 3

Related Questions