如果我有 2 个数组:
arr1: ["1","2"]
arr2: [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]
我想获得:
result: [{id: 1, color: "green"}, {id: 2, color: "yellow"}]
我正在尝试
arr2.filter(
e => arr1.indexOf(e.id) !== -1
);
但结果为空。
答案 0 :(得分:2)
您可以使用 Array.prototype.filter()
和 Array.prototype.some()
方法来获取结果。
const arr1 = ['1', '2'];
const arr2 = [
{ id: 1, color: 'green' },
{ id: 2, color: 'yellow' },
{ id: 3, color: 'red' },
];
const ret = arr2.filter((x) => arr1.some((y) => +y === x.id));
console.log(ret);
另一种使用 Set Object
的解决方案。
const arr1 = ['1', '2'];
const arr2 = [
{ id: 1, color: 'green' },
{ id: 2, color: 'yellow' },
{ id: 3, color: 'red' },
];
const set = new Set(arr1);
const ret = arr2.filter((x) => set.has(x.id.toString()));
console.log(ret);
答案 1 :(得分:2)
您的代码的问题在于,由于您的输入具有不同的类型(id
是数字,但 arr1
是字符串),因此此 arr1.indexOf(e.id) !== -1
将始终为假。
将其中之一转换为这样的数字:
const arr1 = ["1","2"]
const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]
const result = arr2.filter(el => arr1.some(aEl => el.id === +aEl))
console.log(result)
或者,您可以将 id 转换为字符串并使用您现有的代码:
const arr1 = ["1", "2"],
arr2 = [{
id: 1,
color: "green"
}, {
id: 2,
color: "yellow"
}, {
id: 3,
color: "red"
}],
result = arr2.filter(
e => arr1.indexOf(e.id.toString()) !== -1
);
console.log(result)
答案 2 :(得分:0)
另一种解决方案可能是使用 .includes()
方法。
const arr1 = ["1","2"]
const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]
const result = arr2.filter(n => arr1.includes(String(n.id)));
console.log(result);