How to get unique objects from objects array in javascript

后端 未结 4 1435
鱼传尺愫
鱼传尺愫 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"
        }
    ]
    

提交回复
热议问题