You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Object.keys() on an array: getData[sectionName] is an array of entry references, not an object. Using Object.keys() here returns string indices (e.g., "0", "1") instead of the actual entry objects. Looping over these indices breaks getSingleEntry because you're passing invalid IDs.
  2. Sorting too early: The sequence field exists in the individual entries fetched via getSingleEntry, not in the initial reference array. You can't sort references based on a value you haven't retrieved yet.
  3. 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 all sequence values available for sorting.
  • Sorting: We use a comparator function to sort entries numerically by their sequence field.
  • Rendering: After sorting, we loop through the sorted array to display data in the correct order.

内容的提问来源于stack exchange,提问作者frankfurt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:24:13