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

如何筛选含'-usd'的数组元素并替换后输出目标结果?

数组过滤与属性值处理解决方案

嘿,我来帮你搞定这个数组处理的问题~ 你的需求很明确:要从数组里挑出animal属性包含不区分大小写的-usd的元素,把这个后缀去掉,同时还要排除horse和mouse相关的项。

先看看你现在的代码问题:你用了map方法,它会遍历整个数组并返回处理后的字符串数组,但没有过滤掉不需要的元素(比如horse、mouse,还有没带-usd的项),也没有保留原对象的结构,所以才得不到你想要的结果。

正确实现方式

我们可以分两步来做:先筛选出符合条件的元素,再修改它们的animal属性。这样逻辑清晰,也容易维护:

const arr = [ 
  {animal: 'cat-usd', price: 150}, 
  {animal: 'dog-usd', price: 350}, 
  {animal: 'horse', price: 5000}, 
  {animal: 'mouse', price: 50} 
];

const filteredAndProcessedArr = arr
  // 第一步:筛选符合要求的元素
  .filter(item => {
    // 匹配含不区分大小写的'-usd'的animal,同时明确排除horse和mouse
    return /-usd/i.test(item.animal) && !['horse', 'mouse'].includes(item.animal);
  })
  // 第二步:处理符合条件元素的animal属性
  .map(item => {
    // 返回新对象,避免修改原数组的原始数据
    return {
      ...item,
      animal: item.animal.replace(/-usd/gi, '')
    };
  });

console.log(filteredAndProcessedArr);
// 输出结果:[ {animal: 'cat', price: 150}, {animal: 'dog', price: 350} ]

代码解释

  • filter阶段:用正则/-usd/i检测animal属性是否包含不区分大小写的-usd,同时加上!['horse', 'mouse'].includes(item.animal)来明确排除这两个项——哪怕后续数组里出现horse-usd这类情况,也能确保被排除,完全贴合你的需求。
  • map阶段:使用扩展运算符...item复制原对象的所有属性,再覆盖animal属性,把其中的-usd(不区分大小写)替换为空字符串。这样做不会修改原数组的元素,保持了数据的不可变性,是更规范的写法。

如果你想用一步完成的话,也可以用reduce方法:

const filteredAndProcessedArr = arr.reduce((result, item) => {
  if (/-usd/i.test(item.animal) && !['horse', 'mouse'].includes(item.animal)) {
    result.push({
      ...item,
      animal: item.animal.replace(/-usd/gi, '')
    });
  }
  return result;
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:40:38