如何替换对象数组指定key值及根据映射标识获取对应value?
问题解答
1. 替换对象数组中指定key的值
以下是几种常用的JavaScript实现方式:
方式一:遍历修改原数组(forEach)
允许修改原数组时,用forEach遍历匹配目标key,直接更新对应值:
const arr = [{"key": 0, "value": "Example1"}, {"key": 1, "value": "Example2"}]; const targetKey = 0; const newValue = "NewExample1"; arr.forEach(item => { if (item.key === targetKey) { item.value = newValue; } }); // 原数组已更新:[{"key":0,"value":"NewExample1"},{"key":1,"value":"Example2"}]
方式二:生成新数组(map)
需要保留原数组时,用map返回新数组,不修改原数据:
const arr = [{"key": 0, "value": "Example1"}, {"key": 1, "value": "Example2"}]; const targetKey = 1; const newValue = "NewExample2"; const newArr = arr.map(item => { return item.key === targetKey ? {...item, value: newValue} : item; }); // newArr: [{"key":0,"value":"Example1"},{"key":1,"value":"NewExample2"}] // 原arr保持不变
方式三:定位单个目标对象修改(find)
确定数组中只有一个匹配项时,用find直接定位对象修改:
const arr = [{"key": 0, "value": "Example1"}, {"key": 1, "value": "Example2"}]; const targetKey = 0; const newValue = "UpdatedExample1"; const targetItem = arr.find(item => item.key === targetKey); if (targetItem) { targetItem.value = newValue; }
2. 根据标识获取对应对象的value
先建立标识与key的映射关系,再通过映射匹配数组对象取出value:
基础实现代码
const arr = [{"key": 0, "value": "Example1"}, {"key": 1, "value": "Example2"}, {"key": 2, "value": "Example3"}, {"key": 3, "value": "Example4"}]; // 定义标识到key的映射表 const flagToKey = { a: 0, b: 1, c: 2, d: 3 }; // 持有标识a时获取对应value const currentFlag = "a"; const targetKey = flagToKey[currentFlag]; const targetItem = arr.find(item => item.key === targetKey); const resultValue = targetItem ? targetItem.value : "无匹配值"; console.log(resultValue); // 输出: Example1
高效优化版(预转映射)
如果需要多次查找,先把数组转成key-value映射对象,后续直接取值:
// 预生成key到value的映射 const keyToValue = arr.reduce((acc, item) => { acc[item.key] = item.value; return acc; }, {}); // 持有标识a时获取 const currentFlag = "a"; const targetKey = flagToKey[currentFlag]; const resultValue = keyToValue[targetKey] || "无匹配值"; console.log(resultValue); // 输出: Example1
内容的提问来源于stack exchange,提问作者astroboy
相关产品推荐
相关产品推荐

