在JavaScript中用map方法替换for循环

在JavaScript中用map方法替换for循环,javascript,arrays,function,dictionary,refactoring,Javascript,Arrays,Function,Dictionary,Refactoring,我有这个代码正在工作 var allSummaries=[{id:“1”,name:“Example1”},{id:“2”,name:“Example2”},{id:“3”,name:“Example3”},{id:“4”,name:“Example4”},{id:“5”,name:“Example5”},{id:“6”,name:“Example6”},{id:“7”,name:“Example7”},{id:“8”,name:“Example8”},{id:“9”,name:“Exampl

我有这个代码正在工作

var allSummaries=[{id:“1”,name:“Example1”},{id:“2”,name:“Example2”},{id:“3”,name:“Example3”},{id:“4”,name:“Example4”},{id:“5”,name:“Example5”},{id:“6”,name:“Example6”},{id:“7”,name:“Example7”},{id:“8”,name:“Example8”},{id:“9”,name:“Example9”},{id:“10”};
var uniqueSummaries=[“4”、“6”、“9”];
功能摘要(arr1、arr2){
var summariesBasedOnIDs=[];

对于(var i=0;i我将使用和Array.prototype方法的组合:

const result = allSummaries.filter(i => uniqueSummaries.some(u => u === i.id));

console.log(result); // [{id: "4", name: "Example4"}, {id: "6", name: "Example6"}, {id: "9", name: "Example9"}]

我将为此创建一个相当通用的
extract
函数:

const extract = (objs, keys) => objs.filter(obj => keys.some(key => obj.id === key))
extract(allSummaries, uniqueSummaries) //=> [{id: '4', name: 'Example4'}, {id: '6',... ]

我能看到的进一步推广这一点的唯一合理方法是,如果我们允许在
obj
key
上使用函数,而不是简单地测试
id

我认为您需要
filter
而不是
map
——例如
const-extractSpecificSummaries=(arr1,arr2)=>arr1.filter({id}=>arr2.includes))
p.s.您的“代码片段”无效,不能“执行”(代码很好,您只需将javascript放入html块-现已修复)但我的答案与@dhilt的答案不同,因此我会将其保留在这里。谢谢!您能帮我将其重构为ES5吗?