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

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

本文介绍了如何从JavaScript中的对象数组获取唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,如下图所示.有没有一种方法可以使我的数组包含关于 id 的唯一对象?我们可以在下面看到 id 在索引[0]和索引[2]处相同.

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].

有没有一种方法可以获取包含具有唯一 id 的对象的数组,并将 last index 中的第一个对象添加到唯一数组中,而不是第一个对象中目的.在这种情况下,应添加索引为[2]的对象,而不是索引为[0]的对象:

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]:

推荐答案

要针对您的特定情况获取唯一"对象的数组(列表中的最后一个索引),请使用以下方法( 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"
    }
]

这篇关于如何从JavaScript中的对象数组获取唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:35