How to get unique objects from objects array in javascript

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

    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"
        }
    ]
    
    0 讨论(0)
  • 2021-01-29 14:28

    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.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题