PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to sort object by key value in javascript?

 September 08, 2022     ajax, contentful, javascript, jquery     No comments   

Issue

I'm making a code to fetch content from contentful using AJAX. I've success retrieve data and display it, but something is not quite what I want. Because the content that I get is not in the same order as the contentful cms, so I add another field called sequence. So in my code I added a sort() and Object.keys() function before forEach(), but there is no error and data not appears ,does anyone know why data not appears?

If you want to try debugging, you can look at This Codepen.

function renderContentBySection(sectionName, appendElement, numberOfSkeleton, elementAttribute, elementClass){
  $.ajax({
    url : 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA',
    type: 'GET',
    success: function(data){
      const getData = data.fields

      if(getData[sectionName]) {
        if(getData[sectionName] && getData[sectionName].length) {
          getData[sectionName].forEach((item, index) => {
            getSingleEntry(item.sys.id)
          });
        }
      }
    }
  });
}

function getSingleEntry(contentId){
  $.ajax({
    url : `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${contentId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
    type: 'GET',
    success: function(dataKat){
    
      getAssetData(dataKat.fields.image.sys.id, dataKat.fields.sequence)

      $('.data-banner').append(JSON.stringify(dataKat.fields, null, 4))
      $('.data-banner').append('<br>');
    }
  });
}

function getAssetData(assetsId, sequenceId){
  $.ajax({
    url : `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/assets/${assetsId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
    type: 'GET',
    success: function(getAssetsData){
      
      $('.data-image').append(JSON.stringify(getAssetsData.fields, null, 4))
      $('.data-image').append('<br>');
    }
  });
}

$(document).ready(function(){
  renderContentBySection('mainBannerImage', '#carousel-inner', 1, 'banner', 'main-banner-item');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<pre class="data-banner">
  <h4>Get Data Main Banner:</h4>
</pre>
<br>
<pre class="data-image">
  <h4>Get Data for Each Image in Main Banner:</h4>
</pre>


Solution

Because you completely changed the criteria, I will provide an answer for your second ask.

The key to working with multiple batches of asynchronous requests is to gather all the requests, and then listen for them all to complete. Then, do the same thing again with the next batch of requests.

Otherwise, your HTML will print in the order the responses are returned and it will seem random.

Once you have gathered all the completed requests, you can sort() them, then do a forEach through them.

function listenForEntries(arrAllEntryRequests) {
    //set up a listener for when all requests have finished, using "spread operator" (...) to send all requests as parameters to when():
    $.when(...arrAllEntryRequests).done(
        //done:
        function (...arrAllEntryResponses) {
            let arrAllEntries = [];
            //console.log("arrAllEntryResponses", arrAllEntryResponses);

            arrAllEntryResponses.forEach((e) => {
                arrAllEntries.push(e[0].fields);
            });;

            //all images loaded, sort:
            arrAllEntries.sort((a, b) => (a.sequence < b.sequence ? -1 : 1));
            

            //sorting done, get asset data for each. This is also asyncronous so you need to do the same thing as above:    
            let arrAllAssetRequests = [];

            arrAllEntries.forEach((entryData) => {
                //console.log("entryData", entryData);

                $('.data-sequence').append(`
                <ul>
                  <li>
                    Sequence ID: ${entryData.sequence}<br>
                    Title Banner: ${entryData.title}
                  </li>
                </ul>`)
                
                let assetReqObj = getAssetData(entryData.image.sys.id, entryData.sequence);
                arrAllAssetRequests.push(assetReqObj);

            });

            listenForAssets(arrAllAssetRequests);
        }
    );
}

function listenForAssets(arrAllAssetRequests) {
    $.when(...arrAllAssetRequests).done(
        //done:
        function (...arrAllAssetResponses) {
            //all assets loaded, sort:
            arrAllAssetResponses.sort((a, b) => (a[2].sequence < b[2].sequence ? -1 : 1));

            arrAllAssetResponses.forEach((assetData) => {
                //console.log("assetData", assetData);

                if(assetData.length > 0) {
                    $('.data-assets').append(`
                    <ul>
                    <li>
                        Sequence ID: ${assetData[2].sequence}<br>
                        Title Banner: ${assetData[0].fields.title}<br>
                        <img class="img-fluid" src="${assetData[0].fields.file.url}">
                    </li>
                    </ul>`);
                } else {
                    console.error("Something wrong with assetData", assetData);
                }
            });
        }
    );
}

function renderContentBySection(sectionName, appendElement, numberOfSkeleton, elementAttribute, elementClass) {
    $.ajax({
        url: 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA',
        type: 'GET',
        success: function (data) {
            const getData = data.fields

            //move array to inside this function as it's the only place it will be used:
            let arrAllEntryRequests = [];

            if (getData[sectionName]) {
                if (getData[sectionName] && getData[sectionName].length) {
                    getData[sectionName].forEach((item, index) => {
                        arrAllEntryRequests.push(getSingleEntry(item.sys.id));
                    });

                    //once array of requests is created, listen for it to finish:
                    listenForEntries(arrAllEntryRequests);
                }
            }
        }
    });
}

function getSingleEntry(contentId) {
    return $.ajax({
        url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${contentId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
        type: 'GET',
        success: function (dataKat) {
            //do nothing            
        }
    });
}

function getAssetData(assetsId, sequenceId) {
    let $xhr = $.ajax({
        url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/assets/${assetsId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
        type: 'GET',
        success: function (assetData) {
            //do nothing
        }
    });

    $xhr.sequence = sequenceId; //store the sequence for later

    return $xhr;
}

$(document).ready(function () {
    renderContentBySection('mainBannerImage', '#carousel-inner', 1, 'banner', 'main-banner-item');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col-6">
      <div class="data-sequence">
        <span> This is sequence data:</span>
      </div>
    </div>
    <div class="col-6">
      <div class="data-assets">
        <span> This is assets data:</span>
      </div>
    </div>
  </div>
</div>



Answered By - Sean Kendle
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing