根据id匹配替换数组元素 不存在则新增元素的实现方法
JavaScript 实现数组按ID匹配替换/新增元素
核心逻辑非常直接,分两步处理即可:
- 遍历数组,查找是否存在
id与入参对象id一致的元素,记录其索引 - 若找到对应索引,直接用入参对象替换该位置的原有元素;若未找到,将入参对象追加到数组末尾
基础实现(直接修改原数组)
// 你的原始数组 const dataList = [ { "id": 1, "active": 1, "name": "paris" }, { "id": 2, "active": 0, "name": "london" }, { "id": 3, "active": 1, "name": "Australia" }, { "id": 4, "active": 0, "name": "india" } ]; /** * 按id更新或新增数组元素 * @param {Object} newItem 传入的新对象,必须包含id字段 */ function upsertItem(newItem) { // 查找匹配id的元素索引 const matchIndex = dataList.findIndex(item => item.id === newItem.id); if (matchIndex !== -1) { // 匹配到则替换 dataList[matchIndex] = newItem; } else { // 未匹配则新增 dataList.push(newItem); } }
用法示例
// 场景1:替换已有id=4的元素 const updateParams = { "id": 4, "active": 1, "name": "india" }; upsertItem(updateParams); // 执行后原数组中id=4的元素会被新的updateParams替换 // 场景2:新增不存在的id=5的元素 const addParams = { "id": 5, "active": 0, "name": "germany" }; upsertItem(addParams); // 执行后germany会被追加到dataList末尾
可选:不修改原数组的纯函数写法
如果你的项目要求数据不可变(比如React状态更新场景),可以用不修改原数组、返回新数组的写法:
function upsertItemImmutable(sourceList, newItem) { const matchIndex = sourceList.findIndex(item => item.id === newItem.id); if (matchIndex !== -1) { return [ ...sourceList.slice(0, matchIndex), newItem, ...sourceList.slice(matchIndex + 1) ]; } return [...sourceList, newItem]; } // 用法 const newList = upsertItemImmutable(dataList, updateParams);
补充:如果需要兼容IE这类不支持
findIndex的老旧环境,把查找索引的逻辑换成普通for循环即可,判断逻辑完全一致。
内容的提问来源于stack exchange,提问作者Rinky Sharma
相关产品推荐
相关产品推荐

