javascript - 如何遍历数字数组并将它们与具有相同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
如果来自的数字arr1
与arr2
.
所以从这个例子中,我试图从arr2
ID (1,4,5)中获取每个对象
解决方案
您必须过滤 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);
推荐阅读
- java - java:静态变量不能改变值
- java - How do I make Graphics2D draw a tooltip on Mouse Hover
- css - React Navigation - Creating a tab navigator element is not working?
- android - Xamarin Android Image cropper
- javascript - 缺少样式的附加元素
- node.js - 我如何访问 Apostrophe CMS 上页面的子页面小部件
- node.js - 在 node.js 应用程序上保持打开数据库连接是一种好习惯吗?
- assembly - 尝试打印号码时出错
- reactjs - formik表单验证不起作用reactjs
- c++ - PolyHook x64Detour 未连接到 Direct3DCreate9