ES6从数组中过滤/减少对象

时间:2018-04-29 17:47:36

标签: javascript ecmascript-6

鉴于

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))

2 个答案:

答案 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]
相关问题