gpt4 book ai didi

javascript - 检查 JSON 中的重复项

转载 作者:行者123 更新时间:2023-12-02 16:03:20 34 4
gpt4 key购买 nike

我有一个 json 对象:

var object1 = [
{"value1": "1", "value2": "2", "value3": "3",},
{"value1": "1", "value2": "5", "value3": "7",},
{"value1": "6", "value2": "9", "value3": "5",},
{"value1": "6", "value2": "9", "value3": "5",}
]

现在我想要

  • 从该对象中取出每条记录
  • 并检查该记录的精确副本在该对象中出现了多少次?

如果只有 1 个副本,则执行某些操作,如果超过 2 个副本,则执行其他操作。关于 JSON 重复项的答案很少,但它们针对特定值而不是完整记录。

所以我会做记录:

{ "value1": "1", "value2": "2", "value3": "3",}

并将其与object1进行比较。上面的记录将返回 1,因为 object1 内只有 1 个副本

供将来使用。鉴于这些记录

var asset = [
{ value1: "1", value2: "2", value3: "3" },
{ value1: "1", value2: "5", value3: "7" },
{ value1: "6", value2: "9", value3: "5" },
{ value1: "6", value2: "9", value3: "5" }
];

此代码可用于查找重复项:


function countEqual(oo, pp) {
var count = 0;
oo.forEach(function (el) {
var i, equal = true;
for (i in el) {
equal = equal && el[i] === pp[i];
}
equal && count++;
});
return count;
}

var cleaned = [];

asset.forEach(function (itm) {
var unique = true;
cleaned.forEach(function (itm2) {
if (_.isEqual(itm, itm2)) unique = false;
});
if (unique) cleaned.push(itm);
});

for (var i = 0; i < cleaned.length; i++) {
if (countEqual(asset, cleaned[i]) === 1) {
// DO SOMETHING
}
else {
// DO SOMETHING ELSE
}
}

最佳答案

var asset = [
{ value1: "1", value2: "2", value3: "3" },
{ value1: "1", value2: "5", value3: "7" },
{ value1: "6", value2: "9", value3: "5" },
{ value1: "6", value2: "9", value3: "5" }
];

function countEqual(oo, pp) {
var count = 0;
oo.forEach(function (el) {
var i, equal = true;
for (i in el) {
equal = equal && el[i] === pp[i];
}
equal && count++;
});
return count;
}
console.log(countEqual(asset, { value1: "1", value2: "1", value3: "2" })); // 0
console.log(countEqual(asset, { value1: "1", value2: "2", value3: "3" })); // 1
console.log(countEqual(asset, { value1: "6", value2: "9", value3: "5" })); // 2

关于javascript - 检查 JSON 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982157/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com