鉴于
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))
答案 0 :(得分:3)
使用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);

答案 1 :(得分:2)
这是一种方式
Incompatible shapes: [64,14] vs. [14,64]