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

ReactJS嵌套对象列表排序:按人口/价值排序行星内国家

问题描述

现有如下数据:

const planets = [
  {
    planetName: '1',
    countries: [
      {
        countryName:'1',
        population: 432,
        worth: 65,
      },
      {
        countryName:'2',
        population: 9000,
        worth: 10,
      },
      {
        countryName:'3',
        population: 80,
        worth: 200,
      }
    ],
  },
  {
    planetName: '2',
    countries: [
      {
        countryName:'1',
        population: 80,
        worth: 100,
      },
      {
        countryName:'2',
        population: 800,
        worth: 1,
      },
      {
        countryName:'3',
        population: 88,
        worth: 77,
      }
    ],
  },
];

需要在保持行星顺序不变的前提下,将每个行星下的countries数组按population或worth进行排序(比如按population降序得到目标结果)。考虑使用Lodash的chain、map方法,但不清楚具体实现方式,求解决办法。

解决方案

一、原生JavaScript实现

无需依赖第三方库,直接通过map遍历行星数组,对每个行星的countries数组使用sort方法排序即可。map会返回新数组,既不会修改原数据,也能保持行星的原始顺序。

1. 按population降序排序

const sortedByPopulationDesc = planets.map(planet => ({
  ...planet,
  countries: [...planet.countries].sort((a, b) => b.population - a.population)
}));
  • 使用...planet复制行星对象,避免修改原对象;
  • 使用[...planet.countries]复制原国家数组,避免修改原数组;
  • sort((a,b) => b.population - a.population)实现降序排序,若需升序则改为a.population - b.population。

2. 按worth降序排序

const sortedByWorthDesc = planets.map(planet => ({
  ...planet,
  countries: [...planet.countries].sort((a, b) => b.worth - a.worth)
}));

二、Lodash实现

利用Lodash的map和orderBy(或sortBy)方法,结合chain可以实现简洁的链式操作:

1. 按population降序排序

const _ = require('lodash');

const sortedByPopulationDesc = _.chain(planets)
  .map(planet => ({
    ...planet,
    countries: _.orderBy(planet.countries, 'population', 'desc')
  }))
  .value();
  • _.chain()开启链式调用;
  • _.map()遍历行星,复制行星对象并处理countries数组;
  • _.orderBy(数组, 排序字段, 排序方向):第三个参数'desc'表示降序,'asc'表示升序,比原生sort逻辑更直观。

2. 按worth升序排序

const sortedByWorthAsc = _.chain(planets)
  .map(planet => ({
    ...planet,
    countries: _.orderBy(planet.countries, 'worth', 'asc')
  }))
  .value();

如果偏好使用sortBy,可以通过反转数组实现降序:

const sortedByPopulationDesc = _.chain(planets)
  .map(planet => ({
    ...planet,
    countries: _.reverse(_.sortBy(planet.countries, 'population'))
  }))
  .value();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:30:53