[英]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.