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

如何基于嵌套对象属性过滤数组并提取指定字段?

解决方案

你可以通过结合filter和map方法,配合some检查嵌套数组的条件,实现需求:

const filterCityBy = "NY";
const data = [ 
  { name: "Harry", age: 45, totalCities: [{ city: "NY"}]},
  { name: "Mike", age: 36, totalCities: [{ city: "NY"}, {city: "CA"}] }
];

const result = data
  // 第一步:筛选出totalCities包含目标城市的元素
  .filter(item => item.totalCities.some(cityEntry => cityEntry.city === filterCityBy))
  // 第二步:只提取name和age字段
  .map(({ name, age }) => ({ name, age }));

console.log(result);
// 输出结果:[ { name: "Harry", age: 45 }, { name: "Mike", age: 36 } ]

步骤说明:

  • 过滤逻辑:filter方法负责保留符合条件的数组元素。这里用totalCities.some(...)判断当前元素的嵌套数组中是否存在city等于filterCityBy的项——some会在数组中找到第一个满足条件的元素时就返回true,效率较高。
  • 字段提取:map方法遍历过滤后的数组,通过对象解构直接取出name和age属性,返回只包含这两个属性的新对象,匹配你需要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:37:17