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

如何在多维嵌套数据结构中查找key为id的最大数值?

查找嵌套数据中所有card的最大id值

实现思路

  • 先提取所有列表中的cards数组,合并为一个一维数组
  • 将每个card的id(字符串类型)转为数字,确保数值比较的准确性
  • 找出最大数值后,再转回字符串以匹配原id格式

完整代码示例

const data = {
  "lists": {
    "list-1": {
      "id": "list-1",
      "title": "list1",
      "cards": [
        {
          "id": "20",
          "title": "title"
        },
        {
          "id": "2",
          "title": "title"
        }
      ]
    },
    "list-2": {
      "id": "list-2",
      "title": "list2",
      "cards": [
        {
          "id": "4",
          "title": "title"
        },
        {
          "id": "3",
          "title": "title"
        }
      ]
    }
  }
};

// 1. 提取所有列表的cards并合并为一维数组
const allCards = Object.values(data.lists).flatMap(list => list.cards);

// 2. 转换id为数字后找出最大值
const maxIdNumber = Math.max(...allCards.map(card => Number(card.id)));

// 3. 转回字符串格式
const maxId = String(maxIdNumber);

console.log(maxId); // 输出 "20"

分步说明

  • Object.values(data.lists):将data.lists对象的所有值(即两个列表对象)转换为数组
  • flatMap(list => list.cards):遍历每个列表,取出其cards数组并自动合并为一维数组,避免嵌套结构
  • allCards.map(card => Number(card.id)):将每个card的id字符串转为数字,保证数值比较的正确性
  • Math.max(...):展开数字数组,直接获取最大值
  • 最后转为字符串,保持与原id一致的格式

单个列表的最大id查询

如果只需要查询某一个列表的最大id,可以用你已知的方式先获取目标列表,再处理:

const listId = "list-1";
const list = data.lists[listId];
const maxSingleListId = String(Math.max(...list.cards.map(card => Number(card.id))));

console.log(maxSingleListId); // 输出 "20"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:45:56