当我将应用程序移动到Angular2时,我的JSON数组中的过滤器出现问题。在Angular 1.x中更容易。我在过滤器中使用了'unique'
,这将删除所有重复项。
应用程式:
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
}
部分HTML代码:
<div *ngFor='#appsUnique of apps '>
<div class="row dashboard-row">
<div class="col-md-2">
<h4>{{appsUnique.app }}</h4>
</div>
</div>
</div>
结果是:
database_1
database_1
database_2
database_2
我想得到结果:
database_1
database_2
如何从数组中删除重复项?
答案 0 :(得分:10)
Mybe它可以帮助你
#!/bin/bash
# Vars
TODAY=$(date +%d%m%y)
BDIR=/backup/
FLOG="/var/log/mydb_backup.log"
# Backing up the db
su -c "pg_dump --format=c --file=${BDIR}mydb_db_backup.${TODAY} mydb" postgres
if [ $? -eq 0 ]; then
LOG="mydb DB of ${TODAY} backed up!"
else
LOG="Problem to back up mydb DB of ${TODAY}"
fi
# Delete db backup older than 180+ days
find ${BDIR} -type f -mtime +180 -delete
if [ $? -eq 0 ]; then
LOG+=" - Old DB backup deleted"
else
LOG+=" - No Old DB backup to delete"
fi
# Writing result
echo ${LOG} >> ${FLOG}
答案 1 :(得分:6)
我有解决这个问题的方法:)
Array.from(new Set([{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_1",
"host":"my_host1",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
},
{"app":"database_2",
"host":"my_host2",
"ip":"00.000.00.000"
}].map((itemInArray) => itemInArray.app)))
感谢大家的帮助:)
答案 2 :(得分:3)
您可以使用以下方法:
names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
ngOnInit() {
let filteredNames=this.remove_duplicates(this.names);
console.log(filteredNames);
console.log(this.names);
}
remove_duplicates(arr) {
let obj = {};
for (let i = 0; i < arr.length; i++) {
obj[arr[i]] = true;
}
arr = [];
for (let key in obj) {
arr.push(key);
}
return arr;
}
希望这有帮助。
答案 3 :(得分:2)
你也可以使用Observable方法,这很简单。
let filteredData = [];
let arrayData = [{
"app": "database_1",
"host": "my_host1",
"ip": "00.000.00.000"
},
{
"app": "database_1",
"host": "my_host1",
"ip": "00.000.00.000"
},
{
"app": "database_2",
"host": "my_host2",
"ip": "00.000.00.000"
},
{
"app": "database_2",
"host": "my_host2",
"ip": "00.000.00.000"
}];
Observable.merge(arrayData)
.distinct((x) => x.app)
.subscribe(y => {
filteredData.push(y)
console.log(filteredData)
});
答案 4 :(得分:1)
不是循环遍历普通的json数组,而是可以在相应的typescript类中创建另一个数组,并根据需要更改它。在您的HTML中,您可以拥有以下
<div *ngFor='let appsUnique of filteredApps'>
<div class="row dashboard-row">
<div class="col-md-2">
<h4>{{appsUnique.app }}</h4>
</div>
</div>
</div>
接下来,您需要在相应的typescript类中使用此filteredApps数组。
let filteredApps = [];
然后在函数中,您可以创建filterApps,例如在onInit
方法中。
onInit()
{
filteredApps = // filter logic
}
答案 5 :(得分:1)