Angular2 removing duplicates from an JSON array

情到浓时终转凉″ 提交于 2019-12-01 16:11:12

Mybe it can help you

myList = ["One","two","One","tree"];

myNewList =  Array.from(new Set(myList ));

I have a solution for this problem :)

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)))

More about Array.from & Set

Thanks all for help :)

You could use following method:

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;
}

Hope this helps.

You could use Observable approach as well, It is very simple.

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)
  });

instead of looping over the normal json array, you can create another array in your corresponding typescript class, and alter this as you see fit. In your html, you can then have the following

html

 <div *ngFor='let appsUnique of filteredApps'>
    <div class="row dashboard-row">
        <div class="col-md-2">
           <h4>{{appsUnique.app }}</h4>
        </div>
    </div>
</div>

Next, you need this filteredApps array in your corresponding typescript class.

typescript

 let filteredApps = [];

and in a function you can then create that filteredApps, for example in the onInit method.

onInit()
{
    filteredApps = // filter logic
}

You will need trackBy.

Try with:

*ngFor="#appsUnique of posts;trackBy:appsUnique?.app"

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!