这个问题可能是一个简单的迭代,但我陷入了逻辑。
我有一个数据数组,需要根据id和代码进行迭代,并且仅当代码不存在于给定id中时才删除数据。
这是案例场景, 从以下数据来看,
- 有两个名为“GOOGLE”且具有不同 ID 的不同代码 - 有效案例
- 有两个名为“FACEBOOK”且具有不同 ID 的不同代码 - 有效案例
- 有一个名为“TWITTER”的代码不存在于另一个 ID 中 - 无效案例。
在这里,我想根据情况 3 删除这些数据。
{
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}
有人可以帮我解决这个问题吗?
****下面是原始数组数据****
data = [ {
"id" : 381,
"code" : "GOOGLE",
"comment" : "ffff"
}, {
"id" : 381,
"code" : "FACEBOOK",
"comment" : "fff"
}, {
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}, {
"id" : 378,
"code" : "GOOGLE",
"comment" : "rferer"
}, {
"id" : 378,
"code" : "FACEBOOK",
"comment" : "fefehh"
} ]
我尝试了以下操作,但不确定此后如何继续。
而且,我正在使用 Angular 7,如果我得到基于 typescript 的解决方案将会很有帮助。
this.data.forEach((row, index) => {
let value = row.id;
if(originalArray.indexOf(value) == -1) {
console.log(value);
}
originalArray.push(row);
})
最佳答案
试试这个:
data = [ {
"id" : 381,
"code" : "GOOGLE",
"comment" : "ffff"
}, {
"id" : 381,
"code" : "FACEBOOK",
"comment" : "fff"
}, {
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}, {
"id" : 378,
"code" : "GOOGLE",
"comment" : "rferer"
}, {
"id" : 378,
"code" : "FACEBOOK",
"comment" : "fefehh"
} ]
var result = data.reduce((unique, o) => {
if(data.filter(obj => obj.id != o.id && obj.code === o.code).length>=1) {
unique.push(o);
}
return unique;
},[]);
console.log(result);
关于javascript - typescript 中基于两个值的数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113823/