[英]How to remove duplicates from an array object property value?
How can I iterate through object properties and remove duplicates from an array that is the value of that object property? 如何遍历对象属性并从作为该对象属性值的数组中删除重复项?
Original object 原始物件
var navObjects = {
'Components': ['x', 'y', 'x'],
'Document': ['z', 'z', 'z', 'q'],
'Utilities': ['a', 'b', 'c']
}
Desired object 所需对象
navObjects: {
'Components': ['x', 'y'],
'Document': ['z','q'],
'Utilities': ['a', 'b', 'c']
}
What I've tried 我尝试过的
for (let i = 0; i < Object.values(navObjects).length; i++) {
let obj = Object.values(navObjects)[i];
Object.values(obj).filter((item, index) => obj.indexOf(item) === index);
console.log(obj);
}
The arrays remain unchanged after running this block. 运行此块后,阵列保持不变。
You can do it using the Set constructor and the spread syntax : 您可以使用Set构造函数和传播语法来实现 :
const navObjects = { 'Components': ['x', 'y', 'x'], 'Document': ['z', 'z', 'z', 'q'], 'Utilities': ['a', 'b', 'c'] }; for (const key in navObjects) { navObjects[key] = [...new Set(navObjects[key])]; } console.log(navObjects);
This code will help you to achieve your objective. 该代码将帮助您实现目标。
var newNavObjects = {}
var existObjects = {}
for(let key in navObjects) {
let objects = navObjects[key];
newNavObjects[key] = [];
existObjects[key] = {};
for(let object of objects) {
if (!existObjects[key][object]) {
existObjects[key][object] = 1;
newNavObjects[key].push(object);
}
}
}
delete existObjects;
console.log(newNavObjects);
I create new variable for efficiency. 我创建新变量以提高效率。 If we use indexOf to check value inside array exist of not. 如果我们使用indexOf检查数组中是否存在不存在的值。 It will heavier than we check an target variable key in this case existObjects. 在这种情况下,它将比我们检查目标变量键重。 Still this not the best solution but this sure will do. 仍然这不是最好的解决方案,但是可以肯定。 :) :)
You can create a Set
to remove duplicates and get values()
in order to convert it back to an array, like: 您可以创建一个Set
来删除重复项并获取values()
,以便将其转换回数组,例如:
(new Set(['z', 'z', 'z', 'q'])).values()
Let's make a function
of it: 让我们对其function
:
function removeDuplicates(input) {
return (new Set(input)).values();
}
and then use it: 然后使用它:
var navObjects = {
'Components': removeDuplicates(['x', 'y', 'x']),
'Document': removeDuplicates(['z', 'z', 'z', 'q']),
'Utilities': removeDuplicates(['a', 'b', 'c'])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.