如何使用JavaScript根据字符串数组过滤对象数组(匹配id)
问题:根据字符串数组匹配对象id过滤对象数组
输入的对象数组和字符串数组:
const input = [ { id: 1, name: 'first', type: 'first_type', }, { id: 2, name: 'second', type: 'second_type', }, { id: 3, name: 'third', type: 'third_type', }, ]; const chosen_items = ['1','2']
期望输出id匹配的对象数组:
const output = [ { id: 1, name: 'first', type: 'first_type', }, { id: 2, name: 'second', type: 'second_type', }, ]
错误原因说明
你之前的代码用chosen_items.map(id => input[id])是把字符串id当作数组索引取值,而数组索引从0开始计数:input['1']等价于input[1],对应数组第2个元素(id=2);input['2']等价于input[2],对应数组第3个元素(id=3),这就是得到错误结果的原因。
修正后的代码
推荐使用filter配合Set实现,查找效率更高(数据量大时优势明显):
const output = React.useMemo(() => { // 将字符串id集合转为Set,提升查找速度 const chosenIdSet = new Set(chosen_items); // 过滤出id转为字符串后存在于Set中的对象 return input.filter(item => chosenIdSet.has(String(item.id))); }, [input, chosen_items]);
也可以把chosen_items转为数字集合,直接匹配对象的数字id:
const output = React.useMemo(() => { const chosenIdSet = new Set(chosen_items.map(Number)); return input.filter(item => chosenIdSet.has(item.id)); }, [input, chosen_items]);
如果要保留类似你之前的map写法(不推荐,多次find会降低性能),可以这样写:
const output = React.useMemo(() => { return chosen_items.map(idStr => { const targetId = Number(idStr); return input.find(item => item.id === targetId); }).filter(item => item !== undefined); }, [input, chosen_items]);
内容的提问来源于stack exchange,提问作者user19725419
相关产品推荐
相关产品推荐

