[在js中获得对象数组的唯一集合[重复]

问题描述 投票:-2回答:1

我有一个数组

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的唯一数组。这样结果是:

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'}
             ]
javascript node.js arrays object
1个回答
0
投票

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

考虑到这一点,您可以

  • 使用Array.prototype.reduce()遍历源数组并构建一个对象,以id作为键,并使用相应的项目对象作为值
  • Object.values()提取到唯一记录数组中>
  • 以下是概念现场演示的证明:

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%;}
© www.soinside.com 2019 - 2024. All rights reserved.