0

I have this json [object Object],[object Object],[object Object],[object Object],,,[object Object], You can see that there 3 undefined object. When I parse this json file I use this;

for (x=0;x<json.length;x++) {
src=json[x].file.src
list.push(src)
}

When x get 4 (undefined) it stop work. How I can say script to skip this object if this undefined. Example json :


{
   "posts":[
      {
         "id":2236659,
         "updated_at":"2020-05-02T19:58:43.763-04:00",
         "file":{
            "width":933,
            "height":1200,
            "ext":"png",
            "size":1325351,
            "md5":"d1f501df73f7d1daec07a86657baae01"
         }
      },
      {
         "id":2227726,
         "created_at":"2020-04-23T08:06:37.907-04:00",
         "file":{
            "width":933,
            "height":1200,
            "ext":"png",
            "size":1182791,
            "md5":"112cadaaaa89841e8bb7633ba272a409"
         }
      },
      {
         "id":2218681,
         "created_at":"2020-04-16T07:56:56.849-04:00",
         "file":{
            "width":933,
            "height":1200,
            "ext":"png",
            "size":1241188,
            "md5":"c3c13b8e5c72913fa7db03ffc8b6f3c4"
         }
      }
   ]
}
Yusifx1
  • 101
  • 1
  • 9

1 Answers1

1

Try checking if json[i] is not null or undefined using if statement.

var json = [void 0, void 0, void 0, { file: { src: 'test' } }];
var list = [];

for (x = 0; x < json.length; x++) {
  if (json[x]) {
    src = json[x].file.src
    list.push(src)
  }
}

console.log(list);

Or you could use Array.filter and Array.map functions.

var json = [void 0, void 0, void 0, { file: { src: 'test' } }];
var list = json.filter(e => Boolean(e)).map(e => e.file.src);

console.log(list);
TheMisir
  • 4,083
  • 1
  • 27
  • 37