如何根据具有相同值的多个键解析objects列表中的重复数据,其中一个键的值为objects数组

How to parse duplicate data in a list of objects based on multiple keys having the same value, where one key has a value of an array of objects

如标题所述,我正在尝试根据特定的 key:value 对相同来存储重复 object 的列表。

目标是解析信息和return重复项列表。重复项目是指 ID 、标题、项目匹配。 我遇到的主要问题是在每个 object 中,要比较的键之一是一个数组,其中包含一个 object 列表作为值。

您将如何解决这个问题,遍历 object 的数组以确定项目数组是否重复?

下面只是 JSON 数据的一个小例子。

应该return: pk:"0002" 和 pk"0003" 的整个 object,因为它们是重复的。不应 return Object pk:"0001" 和 pk "0004" 因为它们的项目数组:[{}] 不相等。

我的尝试可以确定 ID 和标题是否匹配,但我无法找到匹配的项目:

var data = [
{ pk: "0001", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, { title: "EXTRA", value: "55" }, ], }, 
{ pk: "0002", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0003", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0004", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
];


let duplicates = [];
data.forEach((el, i) => {
  data.forEach((element, index) => {
    if (i === index) return null;
    if (element.ID === el.ID && element.title === el.title) {
      if (!duplicates.includes(el)) {
        //Issue here -> I want to compare the array of items but im not sure how to ?
        //Attempt:
        // I think I understand that this is wrong due to the indexes not sure how you would find this ?

        // if (element.items[i] === el.items[i]) {
        //   duplicates.push(el);
        //   console.log("Test");
        // }

        duplicates.push(el);
      }
    }
  });
});
console.log("duplicates", duplicates);

您可以对具有相同字符串化值的项目进行计数,并将其对象作为结果。

const
    data = [{ pk: "0001", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, { title: "EXTRA", value: "55" }] }, { pk: "0002", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }] }, { pk: "0003", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }] }, { pk: "0004", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }] }],
    keys = ['ID', 'title', 'items'],
    map = data.reduce((m, o) => {
        const
            key = keys.map(k => JSON.stringify(o[k])).join('|'),
            [count = 0, array = []] = m.get(key) || [];
        return m.set(key, [count + 1, [...array, o]]);
    }, new Map),
    duplicates = Array
        .from(map.values(), ([count, array]) => count === 1 ? []: array)
        .flat();

console.log(duplicates);
.as-console-wrapper { max-height: 100% !important; top: 0; }