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

如何在JavaScript中按条件更新对象数组val值并避免重复

数组对象的val更新与去重处理

需求

  • 当数组中对象的id与paramId一致时,将该对象的val值更新为paramValue
  • 若数组中存在其他对象的val值与paramValue重复,则递增这些重复的val值,直到不存在重复情况
  • 返回处理后的完整数组

示例数据

var list = [
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 3, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 2, color: 'indigo' },
];

现有实现的问题

你当前的实现仅筛选出重复项尝试单次递增,存在以下缺陷:

  • 未对目标id的对象执行val更新操作
  • 仅做一次递增,无法处理多次重复的场景(比如多个对象val等于paramValue时,递增后可能仍与其他值重复)
  • 只返回处理后的重复项,未返回完整数组

正确实现方案

function updateAndDeduplicate(list, paramId, paramValue) {
  // 复制原数组,避免修改原数据
  const processedList = JSON.parse(JSON.stringify(list));
  
  // 步骤1:更新目标id的val值
  const targetItem = processedList.find(item => item.id === paramId);
  if (targetItem) {
    targetItem.val = paramValue;
  }
  
  // 步骤2:处理重复的val值
  // 收集所有非null的val值,用于重复检查
  let valSet = new Set(processedList.filter(item => item.val !== null).map(item => item.val));
  
  // 遍历数组,修正非目标id的重复val
  processedList.forEach(item => {
    if (item.id !== paramId && item.val !== null) {
      let currentVal = item.val;
      // 循环递增直到当前val不重复
      while (valSet.has(currentVal)) {
        currentVal++;
      }
      // 更新集合与对象的val
      valSet.delete(item.val);
      item.val = currentVal;
      valSet.add(currentVal);
    }
  });
  
  return processedList;
}

测试结果

测试场景1:paramId = 44, paramValue = 3

const result1 = updateAndDeduplicate(list, 44, 3);
console.log(result1);
// 输出:
[
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 4, color: 'yellow' },
  { id: 44, val: 3, color: 'black' },
  { id: 55, val: 2, color: 'indigo' }
]

测试场景2:paramId = 13, paramValue = 2

const result2 = updateAndDeduplicate(list, 13, 2);
console.log(result2);
// 输出:
[
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 2, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 3, color: 'indigo' }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:35:16