这不起作用
const uniqueArray = this.allusers.user_ids.filter((thing,index) => {
return index === this.allusers.user_ids.findIndex(obj => {
return JSON.stringify(obj) === JSON.stringify(thing);
});
});
this.allusers.user_ids = uniqueArray
这是我的json的示例
0:{
code: "sdsdll"
id: 10
type: "New User"
unit: "Amount"
updated_at: "2019-08-20 09:01:24"
user_ids: (2) [2, 2, 3, 4, 3]
value: "12.00"
__proto__: Object
}
1: {code: "ssddl", id: 9, code: "sklsdsd",...........…}
2: {code: "sdds", id: 11, code: "dsfsdf232",...........…}
我想从对象数组内的user_ids数组中删除重复项。
答案 0 :(得分:1)
尝试(类似这样)*:
不可改变的方式:
this.allusers = this.allusers.map(userObj => {
return Object.assign({}, userObj, {
user_ids: Array.from(new Set(userObj.user_ids))
})
});
(*)迭代对象数组并将每个对象映射到一个新对象,其中new Set(...)
删除了重复的user_id,Array.from(...)
则以数组的形式
突变原始对象:(正如注释中提到的@Kaddath一样,当用户对象发生突变而不是替换时,它保留了其他可能存在的对用户对象的引用)
this.allusers.forEach(userObj => {
userObj.user_ids = Array.from(new Set(userObj.user_ids))
});
答案 1 :(得分:1)
您可以使用set对数组进行重复数据删除。然后,您需要做的就是将其转换回数组:[...new Set(user_ids)]
const data = [{"code":"sdsdll","id":10,"type":"New User","unit":"Amount","updated_at":"2019-08-20 09:01:24","user_ids":[2,2,3,4,3],"value":"12.00"},{"code":"sdsdll2","id":101,"type":"New User 2","unit":"Amount","updated_at":"2019-08-20 09:01:24","user_ids":[4,11,2,2,3,4,4,3],"value":"12.00"}];
const out = data.map(({ user_ids, ...rest }) => {
const dedupedIds = [...new Set(user_ids)];
return { user_ids: dedupedIds, ...rest };
});
console.log(out);
答案 2 :(得分:1)
看起来您的allusers
是一个数组,因此无法在其上调用.user_ids
。您可以遍历它,并使用Set处理每个元素的user_ids
字段。
let allusers = [{code: "sdsdll",id: 10,type: "New User",unit: "Amount",updated_at: "2019-08-20 09:01:24",user_ids: [2, 2, 3, 4, 3],value: "12.00"},{code: "sdsdll2",id: 101,type: "New User 2",unit: "Amount",updated_at: "2019-08-20 09:01:24",user_ids: [4, 2, 2, 3, 4, 4, 5],value: "12.00"}];
allusers.forEach((user) => user.user_ids = [...new Set(user.user_ids)]);
console.log(allusers);
答案 3 :(得分:0)
如果要删除重复的值,可以执行以下操作:
var user_ids = Array.from(new Set(user_ids));