访问嵌套对象数组的所有单个值?

Accessing all Individual Values of a Nested Object Array?

我正在尝试访问每个项目的每个列表对象的单独计数值,以便在数组中使用它们。我尝试了各种地图方法,但它一直返回未定义。我需要一种动态方法来收集这些计数,以便在添加更多列表、项目、位置和计数时,它会更新。

数据:

const data = [
  {
    name: "List1",
    items: [
      {
        name: "Item1",
        locations: [
          { position: "a", count: 20 },
          { position: "b", count: 30 },
        ],
      },
      {
        name: "Item2",
        locations: [
          { position: "c", count: 40 },
          { position: "d", count: 50 },
        ],
      },
    ],
  },
  {
    name: "List2",
    items: [
      {
        name: "Item3",
        locations: [
          { position: "e", count: 60 },
          { position: "f", count: 70 },
        ],
      },
      {
        name: "Item4",
        locations: [
          { position: "g", count: 80 },
          { position: "h", count: 90 },
        ],
      },
    ],
  },
];

想要的结果:

const onlyCounts = [20,30,40,50,60,70,80,90];

任何提示或信息将不胜感激,谢谢!

如果您因为不确定嵌套对象而需要通用解决方案shape/keys/depth,这里有一个递归解决方案,只要您的数据没有任何循环就可以使用。

const getCounts = (value) =>
  value.flatMap((el) =>
    Object.entries(el).flatMap(([key, value]) => {
      if (key === "count") return [value];
      if (Array.isArray(value)) return getCounts(value);
      return [];
    })
  );

const data = [
  {
    name: "List1",
    items: [
      {
        name: "Item1",
        locations: [
          { position: "a", count: 20 },
          { position: "b", count: 30 }
        ]
      },
      {
        name: "Item2",
        locations: [
          { position: "c", count: 40 },
          { position: "d", count: 50 }
        ]
      }
    ]
  },
  {
    name: "List2",
    items: [
      {
        name: "Item3",
        locations: [
          { position: "e", count: 60 },
          { position: "f", count: 70 }
        ]
      },
      {
        name: "Item4",
        locations: [
          { position: "g", count: 80 },
          { position: "h", count: 90 }
        ]
      }
    ]
  }
];

const getCounts = (value) =>
  value.flatMap((el) =>
    Object.entries(el).flatMap(([key, value]) => {
      if (key === "count") return [value];
      if (Array.isArray(value)) return getCounts(value);
      return [];
    })
  );

console.log(getCounts(data))

真正通用的解决方案

const getFieldArray = (value, field) =>
  value.flatMap((el) =>
    Object.entries(el).flatMap(([key, value]) => {
      if (key === field) return [value];
      if (Array.isArray(value)) return getFieldArray(value, field);
      return [];
    })
  );

console.log(getFieldArray(data, 'count'));