How to get unique objects from objects array in javascript

Deadly 提交于 2021-02-17 07:18:10

问题


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 see below that the id are same at index [0] and index [2].

Is there a way that I can get an array containing objects with unique id and the first object from the last index is added to the unique array rather than the first object. In this case, Object at index[2] should be added instead of object at index[0]:


回答1:


To get an array of "unique" objects(with last index within the list) for your particular case use the following approach (Array.forEach, Array.map and Object.keys functions):

// exemplary array of objects (id 'WAew111' occurs twice)
var arr = [{id: 'WAew111', text: "first"}, {id: 'WAew222', text: "b"}, {id: 'WAew111', text: "last"}, {id: 'WAew33', text: "c"}],
    obj = {}, new_arr = [];

// in the end the last unique object will be considered
arr.forEach(function(v){
    obj[v['id']] = v;
});
new_arr = Object.keys(obj).map(function(id) { return obj[id]; });

console.log(JSON.stringify(new_arr, 0, 4));

The output:

[
    {
        "id": "WAew111",
        "text": "last"
    },
    {
        "id": "WAew222",
        "text": "b"
    },
    {
        "id": "WAew33",
        "text": "c"
    }
]



回答2:


The best way to do this is to modify your data structure into an object itself where each key is one of the IDs:

{
    "WadWA7WA6WAaWAdWA...": {
        "text": "birla"
    },
    "WadWA...": {
        "test": "ab"
    }
}

and so forth. If the data comes from a source formatted that way, you can always map the array of results to this format.




回答3:


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)




回答4:


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.



来源:https://stackoverflow.com/questions/37969864/how-to-get-unique-objects-from-objects-array-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!