比较对象内的键值以进行重复更新 [英] Compare key values within object for duplicate updated
问题描述
这是来自将对象内键值重复进行比较的后续帖子获得后续答案.
This is a follow up post from Compare key values within object for duplicate for a follow up answer.
我有一个对象:
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%地到达那里.
Thanks to help on here (Rick) I was able to get 90% of the way there.
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"]
]
我遇到的问题是,如果有两个匹配的键,这是可行的,但如果有三个或三个以上,它将不起作用(正确).
The issue I am having is that while this works if there are two matching keys it will not work (Correctly) if there are three or more.
推荐答案
如果要为映射中的每个键提供所有匹配项的数组,则需要在首次找到键时从设置数组开始.在随后的比赛中,只需将其推入该数组即可:
If you want to have an array of all matches for each key in you map, you need to start by setting an array when you find a key the first time. On subsequent matches, just push into that array:
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的值的地图,这就是摘要中的最后一位.
If you are only interested in values with more than one hit, you can reduce()
down to a map with only values of length greater than one, which is what the last bit in the snippet does.
这篇关于比较对象内的键值以进行重复更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!