我有一个订阅subject
的组件,该组件返回员工记录并将其放入一个数组中。
importResults: ImportResults[] = [];
constructor(
private _massEmpService: MassEmpService
) {
}
ngOnInit() {
// Subscribe to our subject that lets us know about the added employees
this._massEmpService.importedData.subscribe(obj => {
if (obj) {
// Ensure that we have unique results in our imported data
this.importResults.push(_.uniqBy(obj, 'QID'));
}
});
}
我的问题是,每次我的按钮被点击,这个订阅接收到数据,它就会将新数据推送到已经存在的数据旁边,而不是只添加不存在的记录。
这里是一个关于接收到的单个记录的示例(我输入了一个用户名并单击了搜索)
这里是一个示例,当我添加一个额外的用户时,将前一个用户留在搜索字段中。
如您所见,第一个数组是原始搜索结果。第二个数组包含第一个员工和新员工。
我在这里期望的结果是有一个具有唯一对象的数组。这意味着我的示例中应该有2条记录,因为第一个员工被搜索了两次,他不应该被推入或包括到数组中,因为该对象已经存在。
我是不是错误地使用了这个lodash
函数?QID
也是对象中唯一有效的键(图中没有)。
发布于 2017-07-14 15:44:56
您可以使用RxJS的操作符尝试这样的操作,而不是自己手动检查唯一性:
this._massEmpService.importedData
.filter(obj => obj)
.distinct(src => src.QID)
.subscribe(obj => this.importResults.push(obj));
发布于 2017-07-14 12:52:37
你可以找到第一个对象,无论你想推什么,如果找不到,就推它。例如
importResults: ImportResults[] = [];
import * as _ from 'lodash';
constructor(
private _massEmpService: MassEmpService
) {
}
ngOnInit() {
// Subscribe to our subject that lets us know about the added employees
this._massEmpService.importedData.subscribe(obj => {
if (obj) {
// Ensure that we have unique results in our imported data
const keyExists= this._find((obj);
if(keyExists){
this.importResults.push(obj);
}
}
});
}
在组件中创建查找函数
private _find(cur_obj: any): any{
return _.find(this.importResults, function (importResult: any): boolean {
return importResult.QID === cur_obj.QID;
});
}
,这是一个例子。您可以根据您的对象对其进行更改
发布于 2018-05-03 22:46:48
删除数组中重复项的简单方法是:这里我删除了具有重复名称的项
var myArray= [ { 'name': 'Mac'}, {'name': 'Mac'}, {'name': 'John'} ,{'name': 'Edward'}];
console.log('----------------Before removing-------------');
console.log(myArray);
myArray.forEach((item, index) => {
if (index !== myArray.findIndex(i => i.name === item.name)) {
myArray.splice(index, 1);
}
});
console.log('---------------After removing------------------');
console.log(myArray);
https://stackoverflow.com/questions/45090629
复制相似问题