按属性在对象数组的数组中查找重复项的最短方法

编程入门 行业动态 更新时间:2024-10-18 23:23:30
本文介绍了按属性在对象数组的数组中查找重复项的最短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个对象数组.每个对象都有一个对象数组.我需要查找在特定属性中具有相同值的(内部)对象的重复项.我决定在循环内创建一个循环并使用include.有更短的方法吗?

Hi I have an array of objects. Each object has an array of objects. I need to find duplicates of (inner) objects that have the same value in a specific property. I made up to create a loop inside the loop and use include. Is there a shorter way of doing this?

// Verify that there are no duplicate device names. const streamItemNames = []; for (let i = 0, length1 = validateStreamItemsResults.streamWebSockets; i < length1; i++) { const streamItems = validateStreamItemsResults.streamWebSockets[i].streamItems; for (let y = 0, length2 = streamItems.length; y < length2; y++) { const streamItem = streamItems[i]; const streamItemNameLower = streamItem.streamItemName.trim().toLowerCase(); if (streamItemNames.includes(streamItemNameLower)) { validateStreamItemsResults.errorMessage = `Duplicate stream items found with the name: ${streamItemNameLower}`; return validateStreamItemsResults; } else { streamItemNames.push(streamItemNameLower); } } }

更新:对象的结构如下,例如:(我需要使用是或否来确定是否存在重复的"streamItemName"-在此示例中为-true).

UPDATE: The structure of the objects is the following, for example: (I need to determine with true or false if there are duplicates "streamItemName" - In the case of this example - true).

const childArray1 = [ { streamItemName: 'Name1' }, { streamItemName: 'Name2' }, { streamItemName: 'Name3' }, { streamItemName: 'Name4' }]; const childArray2 = [ { streamItemName: 'Name5' }, { streamItemName: 'Name6' }, { streamItemName: 'Name7' }, { streamItemName: 'Name1' }]; const parentArray = [childArray1, childArray2];

推荐答案

如果您正在寻找更清晰,更短的代码,则可以使用 flatMap 提取每个 streamItemName 放入单个数组中,然后使用 .find 查找是否存在重复项:

If you're looking for clearer, shorter code, you could use flatMap to extract every streamItemName into a single array, then use .find to find if there are any duplicates:

const streamItemNames = validateStreamItemsResults.streamWebSockets.flatMap( socket => socket.streamItems.map( item => item.streamItemName.trim().toLowerCase() ) ); const dupe = streamItemNames.find((name, i, arr) => arr.slice(i + 1).includes(name)); if (dupe) { validateStreamItemsResults.errorMessage = `Duplicate stream items found with the name: ${dupe}`; return validateStreamItemsResults; }

如果您不需要知道重复的名称,则可以通过创建一个Set并将其 .size 与数组的 length进行比较来使其更短.

If you don't need to know the duplicate name, you could make it shorter by making a Set and comparing its .size against the array's length.

更多推荐

按属性在对象数组的数组中查找重复项的最短方法

本文发布于:2023-11-07 06:03:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   最短   组中   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!