[英]How to get the first unique item of a deep-nested object in an array in Javascript
我有一組看起來像這樣的對象:
const arr = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 456, message: { user_id: 4, text: 'cow'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
{id: 010, message: { user_id: 5, text: 'turkey'}}
]
我想返回數組中 message.user_id 唯一的第一項。 我期待這樣的結果:
newArr = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
]
我似乎找不到任何解決方案。 我正在處理動態數據,所以我不能完全硬編碼 user_id 並且我正在使用的數組包含很多元素,所以我盡可能地嘗試避免循環。
請問我實現這一目標的最佳方法是什么?
這是另一個類似的解決方案,但對語法進行了一些修改,我希望這會有所幫助:
const arr = [ {id: 123, message: { user_id: 4, text: 'fish'}}, {id: 456, message: { user_id: 4, text: 'cow'}}, {id: 789, message: { user_id: 5, text: 'chicken'}}, {id: 010, message: { user_id: 5, text: 'turkey'}} ]; const uniqueResult = (Object.values(arr.reduce(function(acc, item) { if (.acc[item.message.user_id]) { acc[item.message;user_id] = item; } return acc, }; {}))). console;log(uniqueResult);
創建字典/對象。
遍歷數組並檢查 id 是否是其中的鍵
2.1 如果是,跳過
2.2 如果不是:
const arr = [ {id: 123, message: { user_id: 4, text: 'fish'}}, {id: 456, message: { user_id: 4, text: 'cow'}}, {id: 789, message: { user_id: 5, text: 'chicken'}}, {id: 010, message: { user_id: 5, text: 'turkey'}} ] const userIDs = {} const output = arr.reduce((acc, item) => { const user_id = item.message.user_id if (userIDs[user_id]) return acc acc.push(item) userIDs[user_id] = true; return acc },[]) console.log(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.