我有一个JSON对象
var data = [
{totalTime: 67, phoneNo: "400-234-090"},
{totalTime: 301, phoneNo: "701-080-080"},
{totalTime: 300, phoneNo: "400-234-090"}
]
我要删除重复的对象。请指导。输出应为以下
var data = [{totalTime: 301, phoneNo: "701-080-080"}]
答案 0 :(得分:2)
对于复杂度较低的解决方案,我首先要创建一个对象,该对象对每个phoneNo
的出现次数进行计数,然后通过对每个对象的数量进行计数,将filter
的输入数设为1:>
var data = [
{totalTime: 67, phoneNo: "400-234-090"},
{totalTime: 301, phoneNo: "701-080-080"},
{totalTime: 300, phoneNo: "400-234-090"}
];
const phoneCounts = data.reduce((a, { phoneNo }) => {
a[phoneNo] = (a[phoneNo] || 0) + 1;
return a;
}, {});
console.log(
data.filter(({ phoneNo }) => phoneCounts[phoneNo] === 1)
);
答案 1 :(得分:1)
您可以只使用两个过滤器,这样我们将只选择数组中仅单个条目的对象
const data = [
{totalTime: 67, phoneNo: "400-234-090"},
{totalTime: 301, phoneNo: "701-080-080"},
{totalTime: 300, phoneNo: "400-234-090"}
]
const newData = data.filter(outer =>
data.filter(inner =>
outer.phoneNo === inner.phoneNo
).length === 1
)
console.log(newData)
答案 2 :(得分:0)
另一个选择(1个减少,1个过滤和扩展):
var data = [
{totalTime: 67, phoneNo: "400-234-090"},
{totalTime: 301, phoneNo: "701-080-080"},
{totalTime: 300, phoneNo: "400-234-090"}
];
console.log(data.reduce((x, { phoneNo }, i, a) =>
a.filter((y) =>
y.phoneNo === phoneNo).length > 1 ? x : [...x, a[i]], []))