我試圖根據匹配的 id 加入三個陣列,但是如果帖子或喜歡是“未定義的”,那么它最終會破壞代碼,我將如何對此應用條件,如果陣列未定義,它應該回傳空如果不是,則應進行過濾。
//sample data
const posts =
[ { _id: 1
, message: 'this is post one'
, likes: [ { _id: 1111 } , { _id: 2222 } ]
, comments: [ { _id: 3333 } , { _id: 4444 } ]
}
]
const comments =
[ { _id: 3333, message: 'this is comment 1' }
, { _id: 4444, message: 'this is comment 2' }
]
const likes =
[ { _id: 1111, user: 'Peter' }
, { _id: 2222, user: 'John' }
]
const newPosts = posts.map(post => ({
...post,
likes: likes.filter(like => post.likes.map(like => like._id).includes(like._id)),
comments: comments.filter(comment => post.comments.map(comment => comment._id).includes(comment._id)),
}))
我試過的
const newPosts = posts.map(post => ({
...post,
likes: likes.filter(like => like === undefined ? '': post.likes.map(likes => likes._id).includes(like._id)),
comments: comments.filter(comment => comment === undefined ? '': post.comments.map(comments => comments._id).includes(comment._id)),
}))
對此的用途是 socket.io 使用三個不同的套接字從我的資料庫發出更改,我能夠獲取包含更改的所有三個陣列,并通過匹配 ID 將它們連接到一個更新的陣列“posts”中,這意味著評論/ likes 陣列有時可能最終為空,因此我想應用條件來檢查它是否未定義。如果它未定義,它應該只回傳一個空陣列的值,否則應該發生 filter() 操作,這是否可能,我已經堅持了一段時間,所以任何幫助將不勝感激。
uj5u.com熱心網友回復:
嘗試這個:
const posts = [{
_id: 1,
message: 'this is post one',
likes: [{
_id: 1111
}, {
_id: 2222
}],
comments: [{
_id: 3333
}, {
_id: 4444
}]
}];
const comments = [{
_id: 3333,
message: 'this is comment 1'
}, {
_id: 4444,
message: 'this is comment 2'
}];
const likes = [{
_id: 1111,
user: 'Peter'
}, {
_id: 2222,
user: 'John'
}];
const newPosts = posts.map((post = {}) => ({
...post,
likes: likes.filter((like = {}) =>
post.likes.find((likeItem = {}) => likeItem._id === like._id)
).map(like => like._id),
comments: comments.filter((comment = {}) =>
post.comments.find((commentItem = {}) => commentItem._id === comment._id)
).map(comment => comment._id),
}));
console.log(newPosts);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348703.html
標籤:javascript
上一篇:Javascript中的私有欄位未顯示在JSON.stringify中
下一篇:GoogleAuth用戶加密屬性
