How to get unique objects from objects array in javascript

后端 未结 4 1475
鱼传尺愫
鱼传尺愫 2021-01-29 13:59

I have an array of objects that looks like the image below. Is there a way by which I can have an array that contains unique objects with respect to id ? We can

4条回答
  •  梦如初夏
    2021-01-29 14:48

    You could create a hash using the id as the key and keeping the value as the entire object:

    var myHash = new Object();
    var i;
    
    for(i = 0; i < yourArray.length; i++) {
        var yourObjId = yourArray[i][id];
        myHash[yourObjId] = yourArray[i];
    }
    

    You would be left with a hash myHash containing objects with unique id's (and only the last object of duplicates would be stored)

提交回复
热议问题