javascript 根据第二个数组输入筛选数组结果[duplicate]

tpxzln5u  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(145)

此问题在此处已有答案

Filter array of objects based on another array in javascript(共10个答案)
6小时前关门了。
我有一个对象数组和一个整数id数组。
我只想在react jsx中拥有id与array匹配的对象数组中的那些条目。
例如:

A = [(0)-> id:'123', name:'john', city:'Newyork']
        [(1)-> id:'345', name:'martin', city:'Tokyo']
        [(2)-> id:'456', name:'lee', city:'Malbonre']
        [(3)-> id:'567', name:'roman', city:'Delhi']
        [(4)-> id:'789', name:'julie', city:'US']

B = [123, 456,567]

我希望得到这样的结果:数组A应该只有

A = [(0)-> id:'123', name:'john', city:'Newyork']
        [(1)-> id:'456', name:'lee', city:'Malbonre']
        [(2)-> id:'567', name:'roman', city:'Delhi']
vlju58qv

vlju58qv1#

filterincludes一起使用

const A = [{id:'123', name:'john', city:'Newyork'},
        { id:'345', name:'martin', city:'Tokyo'},
       {id:'456', name:'lee', city:'Malbonre'},
       { id:'567', name:'roman', city:'Delhi'},
       {id:'789', name:'julie', city:'US'}]

const B = [123, 456,567]

const result = A.filter(i => B.includes(Number(i.id)))

console.log(result)
o4tp2gmn

o4tp2gmn2#

const A = [
    { id: "123", name: "john", city: "Newyork" },
    { id: "345", name: "martin", city: "Tokyo" },
    { id: "456", name: "lee", city: "Malbonre" },
    { id: "567", name: "roman", city: "Delhi" },
    { id: "789", name: "julie", city: "US" }
  ];
  const B = [123, 456, 567];
  const result = A.filter((item, index) => B.includes(Number(item.id)));

https://codesandbox.io/s/new?file=/src/App.js:56-421

相关问题