且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从JavaScript中的对象数组获取唯一对象

更新时间:2022-12-10 17:38:50

要针对您的特定情况获取唯一"对象的数组(列表中的最后一个索引),请使用以下方法( Array.forEach Array.map Object.keys 函数):

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));

输出:

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