1

In my object loop using the earch function how to find the value as "just a string" - or "array" - or "object" - while loop through..?

In case if I find the value as "array" - then i suppose to re-loop the array. But how can i find the value as loop-able or returnable using jquery..?

myobject :

var input = {
    "DashBoard": [

    {
        "title": "DashBoard" //non-loopable
    }, {
        "widget": [{ //loop-able - it could be a object (so loop-able)
            "slide": "To do"
        }, {
            "slide": "Teamspace"
        }, {
            "slide": "Recent Activity"
        }]
    }
    ]}

But using the Jquery type - return always object. what is the way to find the object value to distinguish between value and array or object..?

my try:

$.each(input.DashBoard, function (index, item) {

    console.log(index, $.type(item)); //always return object..!

} )

what would be the correct way..

fiddle is here

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • 1
    See http://stackoverflow.com/questions/218798/in-javascript-how-can-we-identify-whether-an-object-is-a-hash-or-an-array – SaganRitual Aug 05 '13 at 05:21

5 Answers5

2

Use typeof operator to get the type of operand.

typeof item === 'string' or typeof item === 'object'

But when it encounters an array, it just returns it as an object. For that you can use $.isArray method of jQuery

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
2

Checking the constructor (class)?

''.constructor === String
[].constructor === Array
{}.constructor === Object
Rowman Pirce
  • 423
  • 2
  • 8
  • It's useful, just adding little more to it to make a comparison using this - ''.constructor.name === 'String'. Hope this would work better now. – Ashmah Aug 05 '13 at 05:29
  • FF 22, Chrome 28, Opera 12.15, Node 0.8.12 -- Works ''.constructor === String perfect. I see no need to check name – Rowman Pirce Aug 05 '13 at 05:34
0

Use $.isArray() to test for array

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Use underscore.js 's isArray function

It is very useful and lightweight utility library for javascript

It works for almost all browsers.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
Wonjung Kim
  • 1,873
  • 15
  • 18
0

Below is the code you can use to determine if your value is a string/ object or array: if($.isArray(yourVariable)) { // loop } else { //return }

shairya
  • 173
  • 9