如何遍历数字数组并使它们与具有相同ID的对象数组匹配

时间:2020-02-13 15:52:14

标签: javascript arrays object

arr1:[1,4,5]
arr2:[
        { id: 1, title:'title', body:'body'},
        { id: 2, title:'title', body:'body'},
        { id: 3, title:'title', body:'body'},
        { id: 4, title:'title', body:'body'},
        { id: 5, title:'title', body:'body'},
        { id: 6, title:'title', body:'body'},
     ]

在React中,如果arr2中的数字与arr1中对象的ID相匹配,我将尝试获取arr2的整个对象。

因此,在此示例中,我试图从arr2中获得ID为(1,4,5)的每个对象

4 个答案:

答案 0 :(得分:3)

您必须过滤匹配其ID的arr2。

  const arr1 = [1, 4, 5];
  const arr2 = [
    { id: 1, title: "title", body: "body" },
    { id: 2, title: "title", body: "body" },
    { id: 3, title: "title", body: "body" },
    { id: 4, title: "title", body: "body" },
    { id: 5, title: "title", body: "body" },
    { id: 6, title: "title", body: "body" }
  ];

  const result = arr2.filter(item => arr1.includes(item.id));

  console.log(result);

答案 1 :(得分:0)

简单地,过滤来自arr1的具有匹配ID的数据

const arr1 =[1,4,5]
const arr2 =[
        { id: 1, title:'title', body:'body'},
        { id: 2, title:'title', body:'body'},
        { id: 3, title:'title', body:'body'},
        { id: 4, title:'title', body:'body'},
        { id: 5, title:'title', body:'body'},
        { id: 6, title:'title', body:'body'},
];

function findMatchData(sourceData, match) { 
  return sourceData.filter((current) => {
    return match.includes(current.id)
  });
}

console.log(findMatchData(arr2, arr1))

希望对您有帮助!

答案 2 :(得分:0)

您可以将功能Array.prototype.filter()与功能Array.prototype.includes一起使用,以通过id过滤所需的对象。

let arr1 = [1,4,5],
    arr2 = [{ id: 1, title:'title', body:'body'},{ id: 2, title:'title', body:'body'},{ id: 3, title:'title', body:'body'},{ id: 4, title:'title', body:'body'},{ id: 5, title:'title', body:'body'},{ id: 6, title:'title', body:'body'}],
    result = arr2.filter(({id}) => arr1.includes(id));
console.log(result);

答案 3 :(得分:0)

让我在这里提供reduce()find()组合的另一种解决方案。

Array.prototype.reduce()

reduce()方法在数组的每个元素上执行一个reducer函数(由您提供),从而产生单个输出值。

Array.prototype.find()

find()方法返回提供的数组中满足提供的测试功能的第一个元素的值。

尝试以下操作:

const arr1 = [1,4,5];
const arr2 = [
  { id: 1, title:'title', body:'body'},
  { id: 2, title:'title', body:'body'},
  { id: 3, title:'title', body:'body'},
  { id: 4, title:'title', body:'body'},
  { id: 5, title:'title', body:'body'},
  { id: 6, title:'title', body:'body'},
];

const result = arr2.reduce((a, {id,body}) => {
  if (arr1.find(e => id === e)) a.push({id, body});
  return a;
}, []);

console.log(result);

希望对您有帮助!