我想知道如何删除(而不是移除)特定的对象,然后在javascript中对嵌套数组对象进行排序,下面是对数组对象进行排序的函数。我需要排除没有数量属性的对象,然后在javascript中对只有数量的对象进行排序,并映射对象(需要使用exluded obj和sorted 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发布于 2019-03-25 12:44:12
您可以使用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);
发布于 2019-03-25 11:59:39
您可以首先根据每个元素是否具有amount属性将myList筛选为两个列表:
const includesAmount = myList.filter(item => item.hasOwnProperty('amount'));
const excludesAmount = myList.filter(item => !item.hasOwnProperty('amount'));
includesAmount.sort(...)
const finalArray = [...includesAmount, ...excludesAmount];这使得两次遍历myList,但是您可以通过迭代遍历myList并将每个元素推送到其各自的数组来在一次遍历中完成。
发布于 2019-03-25 13:00:12
我不确定为什么上面的答案一定要使用hasOwnProperty()。
简单地检查该属性是否存在会更短且更具可读性:
sortAndFilterProviders() {
const noAmountList = myList(item => !item['amount']);
const amountList = myList(item => item['amount']);
amountList.sort( (a, b) => {
const a1 = a.amount,
b1 = b.amount;
if (a1 == b1) {
return 0;
};
return a1 > b1 ? 1 : -1;
});
console.log(amountList); // check if it is sorted
return [... noAmountList, amountList];
}https://stackoverflow.com/questions/55331070
复制相似问题