How can I get a unique array based on object property using underscore

前端 未结 8 1233
遇见更好的自我
遇见更好的自我 2020-12-29 18:30

I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?

Eg.



        
8条回答
  •  感情败类
    2020-12-29 18:32

    In case you need pure JavaScript solution:

    var uniqueProperties = {};
    
    var notUniqueArray = [ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ];
    
    
    for(var object in notUniqueArray){
       uniqueProperties[notUniqueArray[object]['name']] = notUniqueArray[object]['id'];
    }
    
    var uniqiueArray = [];
    
    for(var uniqueName in uniqueProperties){
       uniqiueArray.push(
         {id:uniqueProperties[uniqueName],name:uniqueName});
    }
    
    //uniqiueArray
    

提交回复
热议问题