问题描述
我有一个对象数组.每个对象都有一个对象数组.我需要查找在特定属性中具有相同值的(内部)对象的重复项.我决定在循环内创建一个循环并使用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
.
这篇关于按属性在对象数组的数组中查找重复项的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!