我有一个数组如:
const cars = [
{ id: 23423, brand: 'bmw', doors: 2, color: 'red' },
{ id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
{ id: 97456, brand: 'citroen', doors: 4, color: 'black' },
{ id: 45784, brand: 'dodge', doors: 2, color: 'red' },
{ id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
{ id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
];
这里我有一个id列表,例如:[45784, 23522]
我想找到使用map,filter或reduce的最佳方法,使用ids数组检索第一个数组中的项目。
由于
答案 0 :(得分:8)
简单如下:
const
cars = [
{ id: 23423, brand: 'bmw', doors: 2, color: 'red' },
{ id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
{ id: 97456, brand: 'citroen', doors: 4, color: 'black' },
{ id: 45784, brand: 'dodge', doors: 2, color: 'red' },
{ id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
{ id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
],
ids = [45784, 23522];
let arr = cars.filter(elem => ids.includes(elem.id));
console.log(arr);
答案 1 :(得分:8)
您可以使用Array#includes
进行过滤。
此提案使用destructuring assignment作为对象的id
属性。
var cars = [{ id: 23423, brand: 'bmw', doors: 2, color: 'red' }, { id: 23452, brand: 'volvo', doors: 4, color: 'gray' }, { id: 97456, brand: 'citroen', doors: 4, color: 'black' }, { id: 45784, brand: 'dodge', doors: 2, color: 'red' }, { id: 23452, brand: 'ferrari', doors: 2, color: 'red' }, { id: 23522, brand: 'bmw', doors: 2, color: 'blue' }],
ids = [45784, 23522],
result = cars.filter(({ id }) => ids.includes(id));
console.log(result);

答案 2 :(得分:3)
从ids
数组转换Set,并使用Array.filter()
仅包含集合中存在的项目:
const cars = [
{ id: 23423, brand: 'bmw', doors: 2, color: 'red' },
{ id: 23452, brand: 'volvo', doors: 4, color: 'gray' },
{ id: 97456, brand: 'citroen', doors: 4, color: 'black' },
{ id: 45784, brand: 'dodge', doors: 2, color: 'red' },
{ id: 23452, brand: 'ferrari', doors: 2, color: 'red' },
{ id: 23522, brand: 'bmw', doors: 2, color: 'blue' }
];
const ids = [45784, 23522];
const idsSet = new Set(ids);
const result = cars.filter(({ id }) => idsSet.has(id));
console.log(result);