【问题标题】:How to sort object keys如何对对象键进行排序
【发布时间】:2022-01-05 18:12:00
【问题描述】:

我目前有一个被映射的对象 (configuration),以便在总结屏幕上显示每个项目。但是,我需要在地图之前对对象进行排序,但无法访问我需要的特定值。

const ConfigComponentSummaryContainer = ({ configuration }) => (
    <Grid container spacing={4}>
      {Object.keys(configuration)
        .map(key => {
          const config = configuration[key];
          if (config && config.length && !restrictList.includes(config[0].component.grouping.toLowerCase())) {
            return config
              .map(c => (
                <Grid item xs={6} ref={componentRef}>
                  <ConfigComponentSummary configuration={c} />
                </Grid>
              ));
          }
          return null;
      })}
    </Grid>
  );

这是配置对象在控制台中的样子:

我需要在组件内部获取一个值 (seq) 以用于排序。如何在映射键之前访问该特定值和排序?

【问题讨论】:

    标签: reactjs sorting object


    【解决方案1】:

    使用排序。您可以像在地图中一样使用键并查找对象,或者使用获取键和值的条目。

    Object.entries(configuration)
      .sort((a, b) => a[1][0].component.seq - b[1][0].component.seq)
      .map(([key, config]) => {}); 
    

    【讨论】:

    • 这对我有用,谢谢!我对.sort 很熟悉,但使用.entries 对我来说很重要。
    【解决方案2】:

    只能使用一种数据结构进行排序,那就是数组。我想您需要将对象转换为在组件中按seq 排序的数组,然后将其用于映射

    【讨论】:

      【解决方案3】:

      您可以使用lodash。它有一个方法sortBy,你应该可以像这样使用它:

      _.sortBy(configuration, "component.seq")
      

      【讨论】:

        猜你喜欢
        • 2023-02-03
        • 2010-11-11
        • 1970-01-01
        • 2020-07-11
        • 2019-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-13
        相关资源
        最近更新 更多