javascript - ES6 过滤/减少数组中的对象

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

最佳答案

使用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/

相关文章:

javascript - 表单显示,同时将 acts-as-taggable-on gem 与 jquery tag-it 插件集成

javascript - 查找类包含文本字符串 JQuery 的跨度

javascript - Node 8.9.4 还需要 babel 吗?

javascript - 如何在 ES6 中实现命名构造函数

javascript - 移动网站推送通知 - session 结束后?

javascript - 将谷歌文档转换为 pdf 导致空白 pdf,谷歌脚本

javascript - 如何读取事件数据属性

javascript - 将值传递到 Redux Saga 中的 `next` 函数

javascript - JS 类字段

javascript - React js getInitialState 转换为 es6 后不起作用