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

如何在JavaScript中遍历对象数组并筛选location为dallas的项?

获取所有location为dallas的条目

你可以用flatMap结合filter来实现,这是最简洁的写法:

const dallasClaims = users.flatMap(user => user.claims)
                          .filter(claim => claim.location === 'dallas');

flatMap会把每个用户的claims数组展开成一个一维数组,再通过filter筛选出location等于'dallas'的项。

如果想用forEach也可以,需要先声明空数组来收集结果:

const dallasClaims = [];
users.forEach(user => {
  user.claims.forEach(claim => {
    if (claim.location === 'dallas') {
      dallasClaims.push(claim);
    }
  });
});

两种方法都能得到目标结果,前者更简洁,后者逻辑更直观,适合刚接触数组方法的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:54:23