【问题标题】:Get unique items from array of objects [duplicate]从对象数组中获取唯一项目[重复]
【发布时间】:2020-09-21 20:44:40
【问题描述】:

我有一个数组

friendList = [
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 2, fName: 'Dam', lName: 'Nary', profilePic: 'dam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'},
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'}, 
             ]

我怎样才能得到这个朋友列表的唯一数组.. 结果是:

friendList = [
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 2, fName: 'Dam', lName: 'Nary', profilePic: 'dam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'}
             ]

【问题讨论】:

  • var uniqueArry = Object.values(friendList.reduce((acc,ele)=>{return {...acc,...{[ele.id]:ele}}},{ }))

标签: javascript node.js arrays object


【解决方案1】:

如果您的friendList 项目应该由唯一的id 属性过滤,您可以利用对象应该具有唯一键的事实。

考虑到这一点,你可以

以下是一个概念验证现场演示:

const friendList = [{id:1,fName:'Sam',lName:'Brian',profilePic:'sam.jpg'},{id:2,fName:'Dam',lName:'Nary',profilePic:'dam.jpg'},{id:3,fName:'Jam',lName:'kent',profilePic:'jam.jpg'},{id:1,fName:'Sam',lName:'Brian',profilePic:'sam.jpg'},{id:3,fName:'Jam',lName:'kent',profilePic:'jam.jpg'},],
             
      friendListMap = friendList.reduce((r,item) => 
        (r[item.id] = item, r), {}),
        
      dedupeFriendList = Object.values(friendListMap)
      
console.log(dedupeFriendList)
.as-console-wrapper{min-height:100%;}

【讨论】:

    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2023-03-21
    • 1970-01-01
    • 2013-05-29
    • 2020-11-13
    相关资源
    最近更新 更多