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

如何实现匹配数组与对象数组并返回指定字段值的getValues函数?

问题:实现getValues函数匹配对应字段值

现有对象数组:

const input = [ 
  {id : "1" , text: "ABC", value: "abc" }, 
  {id : "2" , text: "DEF", value: "def" },  
  {id : "3" , text: "LMN", value: "lmn" } 
]

需要实现getValues函数,满足以下调用要求:

const ids = ["1", "3"]
const values = ["def", "lmn"]
const texts = ["DEF", "LMN"]

getValues(input, ids, "text") // 返回 ["ABC", "LMN"]
getValues(input, values, "id") // 返回 ["2", "3"]
getValues(input, texts, "value") // 返回 ["def", "lmn"]

函数要求:传入匹配数组与目标字段后,返回对象数组中匹配项的对应字段值。

用户尝试的代码(无法实现需求):

function getValues(input1, input2, field){
  const result = input1.map(({id, text, value}) => {
     if(text === input2){
       return input1[field];
     }
  }); 
  return result;
}

修正后的代码
function getValues(input, matchArr, targetField) {
  // 建立映射:所有字段值 -> 对应目标字段的值
  const valueMap = new Map();
  input.forEach(item => {
    Object.keys(item).forEach(key => {
      valueMap.set(item[key], item[targetField]);
    });
  });
  
  // 遍历匹配数组,从映射中取出对应结果
  return matchArr.map(matchItem => valueMap.get(matchItem));
}

原代码问题分析

  • 匹配逻辑错误:原代码仅判断text === input2,但input2是数组而非单个值,且未考虑根据匹配数组匹配所有可能字段。
  • 返回值错误:原代码返回input1[field],input1是整个数组,应返回当前遍历对象的对应字段值。
  • 遍历方式错误:map会遍历所有元素,不匹配的项会返回undefined,不符合需求。

修正思路

  1. 构建映射表:遍历输入数组,将每个对象的所有字段值作为键,对应目标字段的值作为值存入Map,实现快速查找。
  2. 生成结果数组:遍历匹配数组,从Map中直接取出每个匹配项对应的目标字段值,返回结果数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:27:25