我想知道如何排除(而不是删除)特定对象,然后在javascript中对嵌套数组对象进行排序,
下面的函数对数组对象进行排序。我需要排除不具有数量属性的对象,然后在javascript中对仅具有数量的对象进行排序并映射该对象(需要使用排除的obj和排序的obj)。
this.providerList = [{id:"transferwise", amount:"1000"}, {id:"wordlremit", amount:"4000", {id:"instarem", amount:"3000"}, {country: "Singapore", scn: "SG"}, {country: "India", scn: "IN"}];
sortAndFilterProviders() {
let myList = [];
myList = [...this.providerList];
myList.push.apply(myList, this.apiproviderdata.apiproviders);
// var mergeList = myList.concat(this.query);
// console.log(mergeList);
myList.sort(function (a, b) {
var a1 = a.amount, b1 = b.amount;
if (a1 == b1) return 0;
return a1 > b1 ? 1 : -1;
});
this.providerList = [...myList];
return this.providerList;
}
expected output
country: Singapore, India
Sorted Amount : Transferwise , Instarem, Worldremit
最佳答案
您可以使用filter()
创建具有/不具有该属性的数组。然后排序所需的数组。最后,按照以下方式concat()
使用它们:
let providerList = [{id:"transferwise", amount:"1000"}, {id:"wordlremit", amount:"4000"}, {id:"instarem", amount:"3000"}, {country: "Singapore", scn: "SG"}, {country: "India", scn: "IN"}];
let amount = providerList.filter( item => item.hasOwnProperty('amount')).sort((a,b)=> a.amount - b.amount);
let notAmount = providerList.filter( item => !item.hasOwnProperty('amount'));
var res = notAmount.concat(amount)
console.log(res);