给定
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
。通过键 (id
) 从 comments
获取值,并使用 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);
关于javascript - ES6 过滤/减少数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089572/