给定

commentIdList = [2,3]
comments = { 1 : "a", 2: "b", 3: "c", 4: "d" }


需要输出

filteredComments = [ {2:"b"} , {3:"c"} ]


我失败的尝试

const filteredComments = comments.filter((c)=> commentsIdList.map(comment=>c.id === comment))

最佳答案

使用Array.map()迭代commentIdList。通过键(comments)从id获取值,并使用computed property names创建一个新对象:



const commentIdList = [2,3];
const comments = { 1 : "a", 2: "b", 3: "c", 4: "d" }
const filteredComments = commentIdList.map((id) => ({
  [id]: comments[id]
}));

console.log(filteredComments);

09-16 17:19