skip to Main Content

I have this JSON I retrieve from an API that contains null values. How do I better traverse the JSON and abstract the functionality?

const colletionjson = 
      { "collections": 
        [ { "title"          : "Home page"
          , "description"    : null
          , "image"          : null
          } 
        , { "title"          : "Products"
          , "description"    : "Products"
          , "image"          : { "src": "https:www.example.com" } 
          , "products_count" : 3
          } 
        ] 
      } 

$.each(collectionjson, function (key, value) {
  $.each(value, function (key, value) {

    var collectionTitle = value.title;
    var collectionDescription = value.description;

    if (value == "image" && $.isArray(value)) {
      var collectionImage = value.image.src;
    } else {
      var collectionImage = "";
    }
  });
});
  // Do something with the data

2

Answers


  1. if (colletionjson.collections && Array.isArray(colletionjson.collections)) {
      colletionjson.collections.forEach(value => {
        const collectionTitle = value.title;
        const collectionDescription = value.description;
        let collectionImage = '';
        if (value.image && value.image.src) {
          collectionImage = value.image.src;
          // do something with this value
        } 
      })
    }
    
    
    Login or Signup to reply.
  2. you can now use Optional chaining (?.) with ECMAScript 2020

    sample code

    const colletionjson =   // just a name
          { collections: 
            [ { title          : 'Home page'
              , description    : null
              , image          : null
              } 
            , { title          : 'Products'
              , description    : 'Products'
              , image          : { src : 'https:www.example.com' } 
              , products_count : 3
              } 
            ] 
          } 
    
    colletionjson.collections.forEach((collection, i) =>
      {
      let collectionTitle       = collection.title
        , collectionDescription = collection.description  || ''
        , collectionImage       = collection.image?.src || '' 
        ;
      console.log (`index: ${i}, title: ${collectionTitle}, description: ${collectionDescription}, image: ${collectionImage}` )
      })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search