How to get unique objects from objects array in javascript

后端 未结 4 1437
鱼传尺愫
鱼传尺愫 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

    Try this: just add to a new object using id as the key

    var arr = [{id:'123', text: 'a'}, {id:'234', text: 'b'}, {id:'123', text: 'c'}]; 
    var map = new Object();
    for(var i in arr){ map[arr[i].id] = arr[i]; }
    var newArr = [];
    for(var i in map){ newArr.push(map[i]); }
    

    newArr shall contain the 2nd and 3rd object.

提交回复
热议问题