簡體   English   中英

ES6從數組過濾/減少對象

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM