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 中,如果 arr1
中的数字与 arr2
中对象的 ID 匹配,我会尝试获取 arr2
的整个对象>。
因此,在这个示例中,我尝试从 arr2
获取 ID 为 (1,4,5) 的每个对象
最佳答案
您必须过滤与其 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);
关于javascript - 如何循环遍历数字数组并将它们与具有相同 id 的对象数组进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211798/