简体   繁体   English

从数组中获取具有唯一ID的第一个对象,并将其放入新列表中

[英]Take the first objects with unique IDs from an array and put them in new list

I am making a dropdown from json file containing array of objects, the problem is some of the objects have same IDs, and I want to extract only the first objects with unique ID (for example 1, then take the second object with unique ID 2 etc..) and put them in a list. 我正在从包含对象数组的json文件中下拉列表,问题是某些对象具有相同的ID,我只想提取具有唯一ID的第一个对象(例如1,然后采用具有唯一ID 2的第二个对象等),然后将它们放在列表中。 That is, I need a list with unique IDs only. 也就是说,我只需要一个具有唯一ID的列表。

What I have tried so far: 到目前为止我尝试过的是:

var distinctId = [];

for (var i = 0; i < data.length; i++) {
            var id = data[i]["id"];
            if (distinctId[id] == undefined) {
                distinctId[id] = [];
            }
            distinctId[id].push(data[i]);
            console.log(data[i]);
        }

The json file looks something like this: json文件如下所示:

[
{
id: 1,
field1: ...,
field2: ...
},
{
id: 1,
field1: ...,
field2: ...
},
{
id: 2,
field1: ...,
field2: ...
},
{
id: 2,
field1: ...,
field2: ...
},
{
id: 3,
field1: ...,
field2: ...
},
{
id: 3,
field1: ...,
field2: ...
},
]

If all you wish to do is get the first two unique id s of your objects you can do this by mapping your array to an array of id's using .map and destructing assignment . 如果您只想获取对象的前两个唯一id ,则可以通过使用.map销毁分配将数组映射到ID数组来实现。

Once you have done this you can use a set to remove all the duplicate's from the array. 完成此操作后,您可以使用一个集合从阵列中删除所有重复项。 Lastly, you can use .splice to keep the first 2 unique id s from your array: 最后,您可以使用.splice保留数组中的前两个唯一id

 const arr = [{id:1,field1:'foo',field2:'bar'},{id:1,field1:'foo',field2:'bar'},{id:2,field1:'foo',field2:'bar'},{id:2,field1:'foo',field2:'bar'},{id:3,field1:'foo',field2:'bar'},{id:3,field1:'foo',field2:'bar'}], res = [...new Set(arr.map(({id}) => id))].splice(0, 2); console.log(res); 

If you wish to have an array of objects which are unique you can use .reduce to create a new array. 如果希望有一个唯一的对象数组,则可以使用.reduce创建一个新的数组。 Essentially the new array is created by adding the first object from the array into it, then checking if the next object has the same id as that object. 本质上,通过将数组中的第一个对象添加到其中,然后检查下一个对象是否具有与该对象相同的id ,来创建新数组。 To do this we use .every . 为此,我们使用.every If it does have the same id we go to the next object, if the id is different then we can add this to our array. 如果确实具有相同的id则转到下一个对象;如果id不同,则可以将其添加到数组中。 Then when we look at our next object we check if it matches any of the now 2 object id's in our array, if it doesn't we can add it and so on. 然后,当我们查看下一个对象时,我们检查它是否与数组中现在2个对象ID中的任何一个匹配,如果不匹配,则可以添加它,依此类推。

 const arr = [{id:1,field1:'foo1',field2:'bar1'},{id:1,field1:'foo2',field2:'bar2'},{id:2,field1:'foo3',field2:'bar3'},{id:2,field1:'foo4',field2:'bar4'},{id:3,field1:'foo5',field2:'bar5'},{id:3,field1:'foo6',field2:'bar6'}], res = arr.splice(1).reduce((acc, elem) => acc.every(({id}) => id != elem.id) ? [...acc, elem] : acc, [arr[0]]); console.log(res); 

You can reduce your array, and check if there is an element that matches your criteria: 您可以减少数组,并检查是否有符合条件的元素:

your_json_array.reduce((destArray, obj) => {
    if (destArray.findIndex(i => i.id === obj.id) < 0) {
      return destArray.concat(obj);
    } else {
      return destArray;
    }
  }, []);

That will give you another array with the desired data. 这将为您提供具有所需数据的另一个阵列。

You can achieve this by using something along the lines of this, however it may be a better idea to do what I've done in my second example. 您可以通过使用沿此线的东西做到这一点,但它可能是一个更好的主意,做什么,我在我的第二个例子中所做的。 Within the second example, you can see that it's storing a list of all duplicated ID's, the first example will only work for an even number of duplicated ID's... IE if there were three objects with the id property set to a value of 1 , you'd still get the value 1 within the array variable. 在第二个示例中,您可以看到它存储了所有重复ID的列表,第一个示例仅适用于偶数个重复ID的情况... IE,如果有三个对象的id属性设置为1 ,您仍然会在array变量中获得值1

I mean there are other ways in which you could achieve this, you could use a filter function in there somewhere, etc. If you require more documentation on how to use the reduce function, I'd suggest the MDN Docs . 我的意思是,还有其他方法可以实现此目的,您可以在某处使用filter功能,等等。如果您需要更多有关如何使用reduce函数的文档 ,建议您使用MDN Docs

Finally with example 3, that's simply removing all duplicates, making use of more modern syntax and features such as destructuring . 最后,在示例3中,只是简单地删除了所有重复项,从而利用了更现代的语法和功能,例如destructuring

Example 1 例子1

 var objects = [{id: 1,a:'x'},{id:1,a:'x'},{id:2,a:'x'},{id:3,a:'x'}]; var array = objects.reduce((a, i) => { a.indexOf(i.id) == -1 ? a.push(i.id) : a.splice(a.indexOf(i.id), 1); return a; }, []); console.log(array); 

Example 2 例子2

 var objects = [{id: 1,a:'x'},{id:1,a:'x'},{id:2,a:'x'},{id:3,a:'x'}]; var array = objects.reduce((a, i) => { objects.filter(e => e.id == i.id).length == 1 ? a.push(i.id) : null; return a; }, []); console.log(array); 

Example 3 例子3

 const objects = [{id: 1,a:'x'},{id:1,a:'x'},{id:2,a:'x'},{id:3,a:'x'}]; const removeDuplicates = ([...o]) => o.reduce((a, i) => { a.indexOf(i.id) == -1 ? a.push(i) : null; return a }, []); console.log(removeDuplicates(objects)); 

1) To remove duplicates from the original array you can use filter() in conjunction with the optional argument that is passed as this to the filtering method. 1)从原始数组中删除重复可以使用过滤器()结合,其是如通过可选的参数this到过滤方法。

2) To get an array with unique ids you can use map() on the previous result. 2)要获取具有唯一ids的数组,您可以在之前的结果上使用map()

This is shown on next example: 这在下一个示例中显示:

 const input = [ {id: 1, field1: "f1", field2: "f2"}, {id: 1, field1: "f1", field2: "f2"}, {id: 2, field1: "f1", field2: "f2"}, {id: 2, field1: "f1", field2: "f2"}, {id: 3, field1: "f1", field2: "f2"}, {id: 3, field1: "f1", field2: "f2"}, ]; // Remove duplicates elements. let res = input.filter( function({id}) {return !this.has(id) && this.add(id)}, new Set() ); console.log("No duplicates:", res); // Get a map with only the IDs. let ids = res.map(({id}) => id); console.log("Ids:", ids); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何取出对象数组中的唯一 ID 并在最早日期之前返回它们? Javascript - How to take out unique ids in array of objects and return them by earliest date? Javascript JavaScript-如何将所有嵌套数组中的所有对象放入唯一对象的新数组中 - JavaScript - How to put all of the objects from several nested arrays into a new array of unique objects 从对象数组中获取匹配的属性并将它们放入新数组中 - Get matching properties out of array of objects and put them in a new array 提取段落中的所有链接并将其放在列表中 - Take all links from a paragraph and put them in a list 迭代对象数组并将它们放入单个工厂函数的最佳方法是什么? - What is the best way to take iterate an array of objects and put them into individual factory functions? 如何从数组中提取对象以自动将它们放入变量中? - How to extract the objects from an array to put them in variables automatically? 对象数组获得具有唯一 ID 的总数 - Array of Objects get total with unique ids 使用来自对象数组的对象的唯一元素创建新的 object - Create new object with unique elements from objects of array of objects 从数组中取出随机字符串,将其放入新数组中,然后再将其放回旧数组中 - take random string from array, put it in new array, then put it back in old array later 使用ES6从数组ID中删除对象列表 - Delete list of objects based from an array ids using ES6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM