javascript

时间:2016-08-01 15:52:12

标签: javascript

我有一个数组如下:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:0)

试试这个:

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);