首页 > 解决方案 > 如何遍历数字数组并将它们与具有相同ID的对象数组匹配

问题描述

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如果来自的数字arr1arr2.

所以从这个例子中,我试图从arr2ID (1,4,5)中获取每个对象

标签: javascriptarraysobject

解决方案


您必须过滤 arr2 匹配其 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" }
  ];

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

  console.log(result);


推荐阅读