[英]ES6 Filter/reduce an Object from an array
给定
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
获取值,并使用计算出的属性名称创建一个新对象:
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);
这是一种方法
commentIdList.map(commentId => ({ [commentId]: comments[commentId] })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.