javascript中的映射和过滤函数

Map and filter functions in javascript

本文关键字:过滤 函数 映射 javascript      更新时间:2023-09-26

我有一个数组,如下所示:

let allCars = [
    {
        id: 1,
        listID: 2,
        name: "CAR 1",
        url: "Fixed 2016-W24"        
    }, {
        id: 2,
        listID: 2,
        name: "CAR 2",
        url: "Fixed 2016-W24"        
    }, {
        id: 3,
        listID: 3,
        name: "CAR 3",
        url: "Fixed 2016-W24"       
    },{
        id: 1,
        listID: 1,
        name: "CAR 4",
        url: "Fixed 2016-W24"        
    },{
        id: 5,
        listID: 2,
        name: "CAR 5",
        url: "Fixed 2016-W24"        
    }
];

我还有一系列的汽车在卡片上,像这样:

let cardContent = [
    {
    carID: 1,
    listID: 2
  },
  {
    carID: 5,
    listID: 2
  }
]

我正在尝试从allCars获得带有id=1, listID=2id=5, listID=2的汽车。

我试着通过cardContent进行映射,然后从allCars中只过滤那些具有该carID和列表ID的人。但没有成功。

我试过这种

const result = allCars.map(i => {
    return {
    carID: i.carID,
    listID: i.listID
  }
}).filter(a => {
    return ((a.carID === cardContent.carID) && (a.listID === cardContent.listID))
});

这是jsfiddle

有什么建议吗?

您可以使用Array#filterArray#some

let allCars = [{"id":1,"listID":2,"name":"CAR 1","url":"Fixed 2016-W24"},{"id":2,"listID":2,"name":"CAR 2","url":"Fixed 2016-W24"},{"id":3,"listID":3,"name":"CAR 3","url":"Fixed 2016-W24"},{"id":1,"listID":1,"name":"CAR 4","url":"Fixed 2016-W24"},{"id":5,"listID":2,"name":"CAR 5","url":"Fixed 2016-W24"}];
let cardContent = [{"carID":1,"listID":2},{"carID":5,"listID":2}]
const result = allCars.filter(function(e) {
  return cardContent.some(function(a) {
    return e.id == a.carID && e.listID == a.listID;
  })
})
console.log(result);

试试这个:

let allCars = [
    {
        id: 1,
        listID: 2,
        name: "CAR 1",
        url: "Fixed 2016-W24"        
    }, {
        id: 2,
        listID: 2,
        name: "CAR 2",
        url: "Fixed 2016-W24"        
    }, {
        id: 3,
        listID: 3,
        name: "CAR 3",
        url: "Fixed 2016-W24"       
    },{
        id: 1,
        listID: 1,
        name: "CAR 4",
        url: "Fixed 2016-W24"        
    },{
        id: 5,
        listID: 2,
        name: "CAR 5",
        url: "Fixed 2016-W24"        
    }
];
let cardContent = [
    {
    carID: 1,
    listID: 2
  },
  {
    carID: 5,
    listID: 2
  }
]
const output = allCars.filter(car => cardContent.some(card => (car.id === card.carID && car.listID === card.listID)));
console.log(output);