我想从数组中删除对象的每个副本:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
console.log(object.map(i=> [...new Set(i)]))
最后我得像:
const object = [
{ label: "Florida", value: "florida" }
];
如何在我的代码中执行此操作?
答案 0 :(得分:0)
您可以使用2个for循环来实现您的功能。
let result = [];
for(let i=0;i<object.length ;i++) {
let isDuplicate = false;
for(let j=0; j<object.length;j++) {
if(object[i].label === object[j].label && object[i].value === object[j].value && i !== j) {
isDuplicate = true;
}
}
if(!isDuplicate) result.push(object[i]);
}
答案 1 :(得分:0)
无论您希望在数组中保留每个元素的副本数量是多少,都应根据定义Map<Location, number>
创建一个Map并列出每个Location
对象的出现次数。然后,获取每个元素并将其仅附加到数组一次。
type Location = {label: string, value: string};
const object: Location[] = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const objects: Map<Location, number> = new Map();
for (const location of object)
if (objects.has(location))
objects.set(location, objects.get(location) + 1);
else
objects.set(location, 1);
const filtered: Location[] = [];
for (const location of objects)
if (location[1] === 1) // You change 1 to any value depending on how many copies of each you'd like.
filtered.push(location[0];
注意:为清晰起见,这是TypeScript,但概念相同。
答案 2 :(得分:0)
快捷方式:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const a = object.filter((v, i, a) => a.findIndex(t => (t.label ===
v.label && t.value === v.value)) === i);
console.log(a);
答案 3 :(得分:0)
您可以使用ES6集-
const unique = [...new Set(object.map(({value}) => value))].map(e => object.find(({value}) => value == e));
console.log("unique",unique);
//[{label: "SUA", value: "sua"},{label: "Florida", value: "florida"}]
对于您的问题,您可以简单地使用reduce-
const uniq = object.reduce((a,b)=>{return a.value === b.value ? {} :[b]},[])
console.log(uniq);
//[{label: "Florida", value: "florida"}]
答案 4 :(得分:-1)
lodash的简单解决方案
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
result = _.xor(_.uniqWith(object,_.isEqual),object)