1

I have nested JSON which is as following:

var data =  [
   {
      "id":"4",
      "name":"2nd anniversary",
      "date":"2015-12-17",
      "location":"Mumbai",
      "story_body":"Gzjjs jdk djks jdks jdkd jx djdb djd JD djbd djdj d",
      "short_link":"izWfs",
      "created_at":"2015-12-11 03:49:52",
      "path":[
         "\/SupportData\/ImpalzB2B\/uploads\/711453354154623.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544217.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/471453355023537.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544223.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544179.jpg"
      ],
      "update_type":"3"
   },       
   {
     "id":"7",
     "name":"#1styearAnniversary",
     "date":"2016-01-20",
     "location":"Mumbai",
     "story_body":"Bsjsj jdkdk djdkdk dkdkf kdkf dkfj fjfj fjfkjdd djkd",
     "short_link":"FHXh0",
     "created_at":"2016-01-20 23:10:54",
     "path":"\/SupportData\/ImpalzB2B\/uploads\/11453356652175.jpg",
     "update_type":"3"
   },       
   {
      "id":"19",
      "name":"Product qetyfvhchv",
      "description":"Cheers Vgdhvjd hugging",
      "short_link":"jPE7G",
      "created_at":"2016-01-18 05:03:46",
      "path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451453118625255.jpg",
      "update_type":"4"
   },
   {
      "id":"20",
      "name":"F frfgcgj ggvvhv",
      "description":" Vdhsj fgjjchk",
      "short_link":"hMn8K",
      "created_at":"2016-01-18 05:04:16",
      "path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451453118654785.jpg",
      "update_type":"4"
   },       
   {
      "id":"25",
      "name":"Gshsh djdj djdkd dkkd",
      "description":"Bsjjd djjd djdirj dudir",
      "short_link":"dhT6l",
      "created_at":"2016-01-22 05:39:31",
      "path":[
         "\/SupportData\/ImpalzB2B\/uploads\/11453466369930.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/11453466369891.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/11453466369942.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/11453466369934.jpg",
         "\/SupportData\/ImpalzB2B\/uploads\/11453466369939.jpg"
      ],
      "update_type":"4"
   },
   {
      "id":"26",
      "name":"For Healthy Breakfast, head over to our new restaurant in Andheri",
      "description":"Delightful upma",
      "short_link":"CG0i4",
      "created_at":"2016-02-04 06:58:17",
      "path":"\/SupportData\/ImpalzB2B\/uploads\/11454594295456.jpg",
      "update_type":"4"
   },
   {
      "id":"1",
      "body":"#Awesome2Eat",
      "votes":"28",
      "update_type":"7",
      "short_link":"GcKAe",
      "created_at":"2016-02-04 01:28:53",
      "name":"nehil"
   },      
   {
      "id":"10",
      "body":"#Bouncy",
      "votes":"1",
      "update_type":"7",
      "short_link":"JXUxz",
      "created_at":"2016-02-04 00:12:52",
      "name":"nehil"
   },
   {
      "id":"11",
      "body":"#Superman",
      "votes":"0",
      "update_type":"7",
      "short_link":"4Keyd",
      "created_at":"2016-02-04 01:17:36",
      "name":"nehil"
   }       
]

How do I get lenght of path array from Object? I tried which gives wrong length.

for (var key in data) {  
  if(data[key].update_type == '3'){ 
    console.log(data[key].path.length);     // 5 and 49 . It Should be 5 and 1
  } 
};  

Also Is this the right way to get each element of Object? :

for (var key in data) {  
   console.log(data[key].id);    
       $.each(data[key].path, function (i, obj) {
         console.log(obj);
       });
   };

Fiddle link: http://jsfiddle.net/Nehil/2ym3ffo0/

Nehil Mistry
  • 1,101
  • 2
  • 22
  • 51

4 Answers4

3

Because the type of value of data[key].path is not array (second instance), it is a String. And String also has the length attribute which gives the length of string.

make it

for (var key in data) {  
  if(data[key].update_type == '3')
  { 
    if (typeof data[key].path == "string" )
    {
      console.log( 1 );
    }
    else
    {
       console.log(data[key].path.length);     // 5 and 49 . It Should be 5 and 1
       //to print all the elements on the console one by one
       if ( data[key].path && data[key].path.length > 0 )
       {
         data[key].path.forEach( function(value){
           console.log( value );
         } );
       }
    }
  } 
}  
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

You can use forEach loop:

The forEach() method executes a provided function once per array element.

var data = [{
  "id": "4",
  "name": "2nd anniversary",
  "date": "2015-12-17",
  "location": "Mumbai",
  "story_body": "Gzjjs jdk djks jdks jdkd jx djdb djd JD djbd djdj d",
  "short_link": "izWfs",
  "created_at": "2015-12-11 03:49:52",
  "path": [
    "\/SupportData\/ImpalzB2B\/uploads\/711453354154623.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544217.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/471453355023537.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544223.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/90294930451449759544179.jpg"
  ],
  "update_type": "3"
}, {
  "id": "7",
  "name": "#1styearAnniversary",
  "date": "2016-01-20",
  "location": "Mumbai",
  "story_body": "Bsjsj jdkdk djdkdk dkdkf kdkf dkfj fjfj fjfkjdd djkd",
  "short_link": "FHXh0",
  "created_at": "2016-01-20 23:10:54",
  "path": "\/SupportData\/ImpalzB2B\/uploads\/11453356652175.jpg",
  "update_type": "3"
}, {
  "id": "19",
  "name": "Product qetyfvhchv",
  "description": "Cheers Vgdhvjd hugging",
  "short_link": "jPE7G",
  "created_at": "2016-01-18 05:03:46",
  "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451453118625255.jpg",
  "update_type": "4"
}, {
  "id": "20",
  "name": "F frfgcgj ggvvhv",
  "description": " Vdhsj fgjjchk",
  "short_link": "hMn8K",
  "created_at": "2016-01-18 05:04:16",
  "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451453118654785.jpg",
  "update_type": "4"
}, {
  "id": "25",
  "name": "Gshsh djdj djdkd dkkd",
  "description": "Bsjjd djjd djdirj dudir",
  "short_link": "dhT6l",
  "created_at": "2016-01-22 05:39:31",
  "path": [
    "\/SupportData\/ImpalzB2B\/uploads\/11453466369930.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/11453466369891.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/11453466369942.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/11453466369934.jpg",
    "\/SupportData\/ImpalzB2B\/uploads\/11453466369939.jpg"
  ],
  "update_type": "4"
}, {
  "id": "26",
  "name": "For Healthy Breakfast, head over to our new restaurant in Andheri",
  "description": "Delightful upma",
  "short_link": "CG0i4",
  "created_at": "2016-02-04 06:58:17",
  "path": "\/SupportData\/ImpalzB2B\/uploads\/11454594295456.jpg",
  "update_type": "4"
}, {
  "id": "1",
  "body": "#Awesome2Eat",
  "votes": "28",
  "update_type": "7",
  "short_link": "GcKAe",
  "created_at": "2016-02-04 01:28:53",
  "name": "nehil"
}, {
  "id": "10",
  "body": "#Bouncy",
  "votes": "1",
  "update_type": "7",
  "short_link": "JXUxz",
  "created_at": "2016-02-04 00:12:52",
  "name": "nehil"
}, {
  "id": "11",
  "body": "#Superman",
  "votes": "0",
  "update_type": "7",
  "short_link": "4Keyd",
  "created_at": "2016-02-04 01:17:36",
  "name": "nehil"
}]



data.forEach((a) => {  /*ES6 Arrow funtion. can use simple 'function(){}' too*/
  if (typeof a.path == "string") {
    console.log(1);
  } else if(typeof a.path!=='undefined') {
    console.log(a.path.length);
  }else{
    console.log(-1);
  }
})
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
0

This is my solution using UnderscoreJs:

_.each(data, function(item) {
    if (item['update_type'] != '3') return;
    var path = (_.isString(item.path) ? [item.path] : item.path) || [];
    var pathCount = path.length;

    // Log path count for item.
    pathCount && console.log(pathCount);

    // Or log path list for item.
    pathCount && _.each(path, function(pathStr) { console.log(pathStr); });
});
haotang
  • 5,520
  • 35
  • 46
0

repeatedly throughout this answer I use this code:

var path = (item.path && typeof item.path == 'string' ? [item.path] : item.path) || [];

breaking it down, if item.path is truthy, if it's a string, set it to [item.path] (i.e. an array with a single element == item.path), othewise use item.path

if this results in a falsey value (item.path is undefined or null etc) set path = [] an empty array

Now path will always be an array, so .length/.forEach/$.each will work without any issue (except if item.path is something other that string/array/undefined/null of course)

as you already use jquery.each, you could do this

$.each(data, function(i, item) {
    if (item.update_type == '3') {
        var path = (item.path && typeof item.path == 'string' ? [item.path] : item.path) || [];
        console.log(path.length);
    }
});

and

$.each(data, function(i, item) {
    console.log(item.id);
    var path = (item.path && typeof item.path == 'string' ? [item.path] : item.path) || [];
    $.each(path, function (i, obj) {
        console.log(obj);
    });
});

I prefer to use jquery as little as possible

data.forEach(function (item) {
    if (item.update_type == '3') {
        var path = (item.path && typeof item.path == 'string' ? [item.path] : item.path) || [];
        console.log(path.length);
    }
});

and

data.forEach(function (item) {
    console.log(item.id);
    var path = (item.path && typeof item.path == 'string' ? [item.path] : item.path) || [];
    path.forEach(function (obj) {
        console.log(obj);
    });
});

to use forEach you may need this polyfill if you think you may need to support IE8 or less

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87