提问人:imjayabal 提问时间:11/17/2023 最后编辑:imjayabal 更新时间:11/17/2023 访问量:54
如何重置对象重复值的数组设置空值
How to reset array of object duplicate value set empty value
问:
如何将重复值设置为数组对象为空字符串。
const arr = [
{ type: 'F', name: "Fun Box", age: 12 },
{ type: 'X', name: "X Box", age: 13 },
{ type: 'X', name: "X Box", age: 14 },
{ type: 'X', name: "X Box Test", age: 15 },
{ type: 'B', name: "Best Box", age: 16 },
{ type: 'B', name: "Best Box Test", age: 15 },
{ type: 'B', name: "Best Box", age: 17 },
{ type: null, name: "Box One", age: 18 },
];
预期结果如下:
const resultArr = [
{ type: 'F', name: 'Fun Box', age: 12 },
{ type: 'X', name: 'X Box', age: 13 },
{ type: 'X', name: '', age: 14 },
{ type: 'X', name: 'X Box Test', age: 15 },
{ type: 'B', name: 'Best Box', age: 16 },
{ type: 'B', name: 'Best Box Test', age: 15 },
{ type: 'B', name: '', age: 17 },
{ type: null, name: 'Box One', age: 18 }
]
我试过了,但没有得到确切的结果,
arr.map((res, i=index) => {
const getNum = i === 0 ? i : i - 1;
const prev = arr[getNum].name;
if (res.name === prev) {
res.name = '';
}
答:
0赞
Florent M.
11/17/2023
#1
您的函数不正确。它仅将当前值与前一个值进行比较,并始终清除索引 0 处的名称。
更有效的方法是在 map 函数之前初始化一个字符串数组,并在遇到新名称时更新此数组。然后,只需检查数组中是否已存在当前名称。
const existingNames = [];
arr.map((res) => {
if(existingNames.includes(res.name)) {
res.name = '';
} else {
existingNames.push(res.name)
}
return res;
});
评论
0赞
AKX
11/17/2023
这样就地修改了原来的,这通常不是一件好事。arr
1赞
Nina Scholz
11/17/2023
#2
您可以在闭包中获取已查看名称的 Set
,并映射对象或采用具有空属性的新对象。name
const
data = [{ type: 'F', name: "Fun Box", age: 12 }, { type: 'X', name: "X Box", age: 13 }, { type: 'X', name: "X Box", age: 14 }, { type: 'X', name: "X Box Test", age: 15 }, { type: 'B', name: "Best Box", age: 16 }, { type: 'B', name: "Best Box Test", age: 15 }, { type: 'B', name: "Best Box", age: 17 }, { type: null, name: "Box One", age: 18 }],
result = data.map((seen => o => seen.has(o.name) || !seen.add(o.name)
? { ...o, name: '' }
: o
)(new Set));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
评论
0赞
AKX
11/17/2023
如果你在代码审查的情况下看到这个代码,你能立即理解它在做什么吗?
0赞
Nina Scholz
11/17/2023
@AKX,这取决于背景。是的,我能读懂它。
0赞
3limin4t0r
11/17/2023
虽然你也许能读懂它。答案的目的是让 OP 可以理解。鉴于问题中显示的信息,我认为这引起的问题多于答案。
0赞
imjayabal
11/17/2023
更新了确切的数据。希望现在你能理解我为什么提出这个问题:)
2赞
AKX
11/17/2023
#3
在映射
ping 数据以创建新数据时,可以跟踪使用 Set
看到的名称。
const arr = [
{ type: "F", name: "Fun Box", age: 12 },
{ type: "X", name: "X Box", age: 13 },
{ type: "X", name: "X Box", age: 14 },
{ type: "X", name: "X Box Test", age: 15 },
{ type: "B", name: "Best Box", age: 16 },
{ type: "B", name: "Best Box Test", age: 15 },
{ type: "B", name: "Best Box", age: 17 },
{ type: null, name: "Box One", age: 18 },
];
const seenNames = new Set();
const newArr = arr.map((el) => {
if(seenNames.has(el.name)) {
// If we've seen the name already, replace it with an empty string.
return {...el, name: ''};
}
// Record the name, and return the element as-is.
seenNames.add(el.name);
return el;
});
console.log(newArr);
评论