簡體   English   中英

如何按 javascript 中的鍵值對 object 進行排序?

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

我正在編寫代碼以使用 AJAX 從內容中獲取內容。 我已經成功檢索數據並顯示它,但有些東西不是我想要的。 因為我得到的內容和內容豐富的 cms 的順序不同,所以我添加了另一個名為sequence的字段。 所以在我的代碼中,我在forEach()之前添加了一個sort()Object.keys() function ,但是沒有錯誤並且沒有出現數據,有誰知道為什么沒有出現數據?

如果您想嘗試調試,可以查看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>

因為您的數據是異步加載的,所以您需要創建一個請求隊列,並等待它們全部完成。

我在下面評論了我的代碼,以便您了解它是如何工作的。

首先,您需要大量使用擴展運算符...來處理未知數量的數組元素。 https://stackoverflow.com/a/35169449/1410567

其次,您需要使用$.when(...array).done(function(...results) {來了解請求何時完成。( https://blog.kevinchisholm.com/javascript/jquery/using -jquery-deferred-to-manage-multiple-ajax-calls/ )

第三,您需要使用Array.sort()對對象數組進行排序,比較它們的sequence ,並返回 1 或 -1 對它們進行排序。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 //create an empty array to hold the queue: let allImageRequests = []; function listenForImages() { //set up a listener for when all requests have finished, using "spread operator" (...) to send all requests as parameters to when(): $.when(...allImageRequests).done( //done: function (...arrAllImagesResp) { let arrAllImages = []; console.log("arrAllImagesResp", arrAllImagesResp); arrAllImagesResp.forEach((e) => { console.log(e); arrAllImages.push(e[0].fields); });; //all images loaded, sort: arrAllImages.sort((a, b) => (a.sequence < b.sequence? -1: 1)); console.log("done", arrAllImages); //sorting done, display results: $('.data-image').append("\n\n<strong>All Images Sorted:</strong> \n\n" + JSON.stringify(arrAllImages, null, 4)); } ); } $.ajax({ url: 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA', type: 'GET', success: function (data) { console.log("got data", data); const getData = data.fields.mainBannerImage $('.data-banner').append(JSON.stringify(getData, null, 4)) $('.data-banner').append('<br>'); getData.forEach((item, index) => { //add requests to our queue: allImageRequests.push(getImageAssets(item.sys.id)); }); listenForImages(); } }) function getImageAssets(assetId) { //I added a return here, so the XHR objects will be push()'d to the allImageRequests queue array: return $.ajax({ url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${assetId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`, type: 'GET', success: function (assetsData) { const getAssetsData = assetsData.fields $('.data-image').append(JSON.stringify(getAssetsData, null, 4)) $('.data-image').append('<br>'); } }) }
 <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>

因為您完全改變了標准,所以我將為您的第二個問題提供答案。

處理多批異步請求的關鍵是收集所有請求,然后監聽它們以完成。 然后,對下一批請求再次執行相同的操作。

否則,您的 HTML 將按照返回響應的順序打印,並且看起來是隨機的。

一旦你收集了所有完成的請求,你可以對它們進行sort() ,然后通過它們執行一個forEach

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM