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

如何遍历含数组的对象并按price字段删除指定元素?

正确实现方法

先明确你代码里的几个核心问题:

  • 变量名不匹配:你定义的目标对象是newArr,但遍历用了未定义的currentPrices,会直接触发引用错误。
  • Object.entries().map()返回的是由单个键值对对象组成的数组,不是完整的目标对象结构,需要用Object.fromEntries()将数组转回对象。
  • 若仅需处理month数组,没必要遍历所有属性,直接操作更高效。

方案1:仅处理month数组(匹配你的需求)

const targetPrice = 10; // 指定要删除的price值
const originalObj = {
  month: [
    { count: 1, price: 10, _id: '65434684e7c9298236522446' },
    { count: 2, price: 20, _id: '463239a84e7c929345tqgr46' },
  ],
  year: [{}],
  weak: [{}],
  day: [{}],
};

// 生成新对象,不修改原对象(推荐immutable操作)
const newObj = {
  ...originalObj,
  month: originalObj.month.filter(item => item.price !== targetPrice)
};

console.log(newObj.month); // 输出仅包含price为20的对象

方案2:批量处理所有数组属性(如需全局过滤)

如果需要对所有数组类型的属性执行相同的price过滤逻辑,可以用以下方式:

const targetPrice = 10;
const originalObj = { /* 你的原始对象 */ };

const newObj = Object.fromEntries(
  Object.entries(originalObj).map(([key, value]) => {
    // 仅处理数组类型且项包含price字段的属性
    if (Array.isArray(value)) {
      return [key, value.filter(item => item.price !== targetPrice)];
    }
    // 非数组属性直接保留原内容
    return [key, value];
  })
);

原代码的修正版本

如果坚持用你最初的遍历思路,修正后的代码如下:

const targetPrice = 10;
const originalObj = { /* 你的原始对象 */ };

const newObj = Object.fromEntries(
  Object.entries(originalObj).map(([key, value]) => 
    ([key, value.filter(dateItem => dateItem.price !== targetPrice)])
  )
);

这里补充了Object.fromEntries()转换数组为对象,修正了变量名,并明确了要删除的价格值targetPrice(你原代码中的price未定义)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:35:39