我有一个包含不同服务器配置的对象数组。例如,具有 URL、用户名、密码等属性的对象... 我想防止用户在此对象数组中输入重复的服务器配置对象。我该怎么做?
我不是在使用"==="寻找参考检查。它只检查引用。我需要比较每个对象的所有属性,并且仅在数组中不存在配置时才推送。
Array:
[{
"url": "test.com",
"username": "Rishabh",
"apiKeys": "test",
"jobName": "testJob"
}, {
"url": "test2.com",
"username": "Rishabh2",
"apiKeys": "test",
"jobName": "testJob"
}]
Input:
{
"url": "test2.com",
"username": "Rishabh2",
"apiKeys": "test",
"jobName": "testJob"
}
对于上述数组和输入,结果应为负数(即重复输入(。
这个问题,如何确定对象是否在数组中,没有回答我的问题。它清楚地表明"car1和car4包含相同的数据,但是不同的实例,它们应该被测试为不相等。我想要相反的。如果 2 个对象包含相同的数据,则应将它们视为相等。 另外,我想比较属性名称和值。
以防对象中键的出现/顺序始终相同。然后,您可以使用下面的代码片段来串化对象并检查它们是否相同。
var duplicateEntry=false;
existingConfigurationArr.forEach(function(item) {
if(JSON.stringify(userInputObject) == JSON.stringify(item)){
duplicateEntry=true;
};
});
alert(duplicateEntry);
如果 JSON 对象的键顺序不确定。 遵循按键对 JavaScript 对象进行排序。 并在比较对象之前在上面的代码片段中使用它。
如果不想使用某些比较代码,可以利用架构验证包。比如@hapi/joi
(https://github.com/hapijs/joi(。代码将如下所示
const Joi = require("@hapi/joi");
const input = [{
"url": "test.com",
"username": "Rishabh",
"apiKeys": "test",
"jobName": "testJob"
}, {
"url": "test2.com",
"username": "Rishabh2",
"apiKeys": "test",
"jobName": "testJob"
}, {
"url": "test2.com",
"username": "Rishabh2",
"apiKeys": "test",
"jobName": "testJob"
}];
const schema = Joi.array().items(Joi.object({
"url": Joi.string().required(),
"username": Joi.string().required(),
"apiKeys": Joi.string().required(),
"jobName": Joi.string().required()
})).unique();
console.log(schema.validate(input));
这里的键是unique();
,它适用于 n 个字段。无需手动检查。
响应将告诉您是否有重复项。在这种特殊情况下error
将包含
"value" position 2 contains a duplicate value
否则,错误将为空。
希望这有帮助。