JavaScript对象按键值排序及Contentful数据排序后不显示问题排查
Solution
Your problem comes down to two critical mistakes: misusing Object.keys() on an array, and trying to sort entries before fetching the sequence data they contain. Here's how to fix it:
Core Issues
Object.keys()on an array:getData[sectionName]is an array of entry references, not an object. UsingObject.keys()here returns string indices (e.g.,"0","1") instead of the actual entry objects. Looping over these indices breaksgetSingleEntrybecause you're passing invalid IDs.- Sorting too early: The
sequencefield exists in the individual entries fetched viagetSingleEntry, not in the initial reference array. You can't sort references based on a value you haven't retrieved yet. - Async race condition: Even if you sorted references, AJAX calls are asynchronous—responses could come back out of order, making the final display unsorted anyway.
Corrected Code
We'll use promises to fetch all entries and assets first, sort by sequence, then render in order:
function renderContentBySection(sectionName) { return $.ajax({ url: 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA', type: 'GET' }).then(data => { const getData = data.fields; if (getData[sectionName] && getData[sectionName].length) { // Convert each reference to a promise that fetches full entry + asset const entryPromises = getData[sectionName].map(item => getSingleEntry(item.sys.id)); // Wait for all fetches to complete return Promise.all(entryPromises); } return []; }); } 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' }).then(dataKat => { // Fetch associated asset and combine with entry data return getAssetData(dataKat.fields.image.sys.id).then(assetData => { return { entry: dataKat.fields, asset: assetData.fields, sequence: dataKat.fields.sequence }; }); }); } function getAssetData(assetsId) { return $.ajax({ url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/assets/${assetsId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`, type: 'GET' }); } $(document).ready(function() { renderContentBySection('mainBannerImage') .then(entriesWithAssets => { // Sort entries by sequence number (ascending order) const sortedEntries = entriesWithAssets.sort((a, b) => a.sequence - b.sequence); // Render sorted data sortedEntries.forEach(item => { $('.data-banner').append(JSON.stringify(item.entry, null, 4)); $('.data-banner').append('<br>'); $('.data-image').append(JSON.stringify(item.asset, null, 4)); $('.data-image').append('<br>'); }); }) .catch(error => { console.error('Failed to fetch data:', error); }); });
Explanation
- Promises:
Promise.all()waits for all entry and asset fetches to finish, ensuring we have allsequencevalues available for sorting. - Sorting: We use a comparator function to sort entries numerically by their
sequencefield. - Rendering: After sorting, we loop through the sorted array to display data in the correct order.
内容的提问来源于stack exchange,提问作者frankfurt
相关产品推荐
相关产品推荐

