这是来自 Compare key values within object for duplicate 的后续帖子以获得后续答复。
我有一个对象:
myObj = {
attendent-0-id:"123",
attendent-0-name:"Bob Smith",
attendent-1-id:"1234",
attendent-1-name:"Alex Smith",
attendent-2-id:"123",
attendent-2-name:"Charlie Smith",
attendent-0-id:"123",
attendent-0-name:"John Smith",
attendent-maxGuest:1,
attendent-party-name:"",
}
多亏了这里的帮助 (Rick),我才完成了 90% 的事情。
function errorOnDuplicateIds(obj) {
const map = {};
const pattern = /^attendent-\d+-id$/;
for (const key of Object.keys(obj)) {
if (pattern.test(key)) {
const value = obj[key]
if (value in map) {
map[value] = [map[value], key];
} else {
map[value] = key
}
}
}
return map;
}
我得到的返回是:
array:[
0:(2) ["attendent-0-name", "attendent-1-name"]
1:"attendent-2-name"
]
但我正在寻找:
array:[
0:(2) ["attendent-0-name", "attendent-1-name", "attendent-2-name"]
]
我遇到的问题是,如果有两个匹配的键,它就可以工作,但如果有三个或更多,它就不会(正确地)工作。
最佳答案
如果您想要映射中每个键的所有匹配项的数组,您需要首先在第一次找到键时设置一个数组。在随后的比赛中,只需插入该数组:
const myObj = {'attendent-0-id': "1234",'attendent-0-name': "Bob Smith",'attendent-1-id': "123",'attendent-1-name': "Alex Smith",'attendent-2-id': "123",'attendent-2-name': "Charlie Smith",'attendent-maxGuest': 1,'attendent-party-name': "",};
function errorOnDuplicateIds(obj) {
const map = {};
const pattern = /^attendent-\d+-id$/;
for (const key of Object.keys(obj)) {
if (pattern.test(key)) {
const value = obj[key]
if (value in map) {
map[value].push(key); // push a new value
} else {
map[value] = [key] // set it to an array
}
}
}
/* if you only want lengths > 1
otherwise just return map */
let filtered = Object.entries(map)
.reduce((a, [key, value]) => value.length > 1 ? Object.assign(a, {[key]: value}) : a, {})
return filtered;
}
console.log(errorOnDuplicateIds(myObj));
如果您只对具有多个命中的值感兴趣,您可以reduce()
向下生成一个只有长度值大于 1 的映射,这就是代码片段中的最后一位
关于javascript - 比较对象内的键值是否重复更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51636744/