重复的值正在存储到对象数组中
根据给定的userID
需要删除重复的userId
,
如果存在,则不执行任何操作,否则将userId
推入teamSocketsList数组
但是使用下面的代码,重复的值被存储到一个数组teamSocketsList
var TeamUser = {
userId : userID,
socketId : socket.id
}
var i = $.inArray( userID, teamSocketsList );
if(i == -1){
teamSocketsList.push(TeamUser);
}else{
teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
return value != userID;
});
}
实际结果:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
预期结果:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
编辑:
在这里,我希望根据条件将userID
推入数组teamSocketsList
中,如果当前列表中的所有给定userID
匹配项都应该返回false或没有。否则,(如果不包括,则将其保存)具有自动生成的socketId
值的数组中
我尝试实现的逻辑是检查该数组是否为空,然后遍历数组列表中的所有元素,以便每当将userID
用作输入时,都必须检查条件,然后推动该元素。
根据当前提出的答案,它将存储重复的值,然后将其排序并分配回teamSocketsList
,这很好。
答案 0 :(得分:1)
除了已经提到的值/减少之外,您还可以利用Set()
:
const myArray = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const unique = (arr, key) => {
const keys = new Set();
return arr.filter(el => !keys.has(el[key]) && keys.add(el[key]));
};
console.log(unique(myArray, "userId"));
与其他响应相反,我可以指出,使用此方法更容易更改数组和键,而无需添加代码。
答案 1 :(得分:0)
与reduce
一起使用Object.values
。创建一个键为userId
的对象。如果密钥不存在,请创建密钥,然后使用Object.values
获取所需的输出。
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
];
const output = Object.values(input.reduce((accu, {userId, socketId}) => {
if(!accu[userId]) accu[userId] = {userId, socketId};
return accu;
}, {}));
console.log(output);
答案 2 :(得分:0)
此函数如何在数组中传递和获取结果的键
const convertArrayToObjecByID = ({ array, key }) =>
array.reduce((obj, item) => {
return { ...obj, [item[key]]: item };
}, {})
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const myObject = convertArrayToObjecByID({ array:input, key:'userId' })
console.log({myObject})
//then if you want it as an array
console.log(Object.keys(myObject).map(item => myObject[item]))
答案 3 :(得分:0)
您可以将数据存储在对象(键值对)中,并避免添加重复的数据。 例如:
var teamSocketsList = {};
var TeamUser = {
userId : userID,
socketId : socket.id
}
teamSocketsList[TeamUser.userId] = TeamUser;
然后,如果要将新用户添加到teamSocketsList,则可以轻松地(无需遍历数组中的所有元素)检查是否存在具有该ID的teamUser。
if(teamSocketsList[TeamUser.userId]) // team user exists in the list