问题描述
我有一个包含6个元素的数组。每个元素都有3个属性:id
,value
和friends
。
在我的代码中,我通过向某些元素的friends
属性添加新值来操纵数组,但是在某些情况下,这会导致friends
属性中的值重复。例如,在下面的myArray
中,元素5不能两次与元素1成为朋友-他们不是朋友。
const myArray = [
{"id": 1,"value": 75,"friends": 3},{"id": 2,"value": 40,"friends": 4},{"id": 3,"value": 60,"friends": 5},{"id": 4,"value": 62,"friends": [6,1]},{"id": 5,"value": 55,"friends": [1,{"id": 6,"value": 33,"friends": [2,1]}
];
我想要的输出看起来像这样:
myArray
我是javascript新手,不确定从何处开始。我的直觉是首先获取所有const myArray = [
{"id": 1,"friends": 1},1]}
];
,然后应用一些过滤功能:
friends
但这显然行不通。
解决方法
myArray.map(elem => {
if(typeof(elem.friends) == 'object') {
elem.friends = [... new Set(elem.friends)]
if(elem.friends.length == 1) {
elem.friends = elem.friends[0]
}
}
});
,
尝试一下。
const myArray = [
{"id": 1,"value": 75,"friends": 3},{"id": 2,"value": 40,"friends": 4},{"id": 3,"value": 60,"friends": 5},{"id": 4,"value": 62,"friends": [6,1]},{"id": 5,"value": 55,"friends": [1,{"id": 6,"value": 33,"friends": [2,1]}
];
const friendList = myArray.map(getFriends);
function getFriends(element) {
if(element.friends.length > 0) {
element.friends = [... new Set(element.friends)]
if(element.friends.length === 1) {
element.friends = element.friends[0];
}
}
return element;
}
console.log(friendList);
,
我认为解决此问题的最简单方法是始终用集合表示friends
值。因此您的数组如下所示:
const myArray = [
{"id": 1,"friends": new Set([3])},"friends": new Set([4])},"friends": new Set([5])},"friends": new Set([6,1])},"friends": new Set([1,"friends": new Set([2,1])}
];
然后添加一个朋友,您要做的就是:
myArray[i]["friends"].add(7);
重复项会自动处理。
,您可以编写执行清理的功能。
const myArray = [
{"id": 1,1]}
];
const getDataWithoutDup = (data) => {
// Loop through the array
data.forEach(val => {
// Check if friends property in the object is an array
if(typeof(val.friends) == 'object') {
let newVal = [...new Set(val.friends)];
// Add the new value of friends
val.friends = newVal.length > 1 ? newVal : newVal[0];
}
})
console.log(data);
return data;
}
getDataWithoutDup(myArray);