我有這個 json,我需要對它進行排序并找到一個在 avatarUrl 中有 url 的物件并將其設定為第一個物件。我們如何在 angular 中做到這一點?
[
{
"id": 1,
"avatarUrl": null,
"age": 20
},
{
"id": 2,
"avatarUrl": null,
"age": 22
},
{
"id": 3,
"avatarUrl": "https://get-edu.kz/wp-content/uploads/2020/04/helpbox-contact.jpg",
"age": 20
},
{
"id": 4,
"avatarUrl": null,
"age": 18
}
]
uj5u.com熱心網友回復:
從您的示例中,我制作了此打字稿代碼:
let yourArray = [
{
"id": 1,
"avatarUrl": null,
"age": 20
},
{
"id": 2,
"avatarUrl": null,
"age": 22
},
{
"id": 3,
"avatarUrl": "https://get-edu.kz/wp-content/uploads/2020/04/helpbox-contact.jpg",
"age": 20
},
{
"id": 4,
"avatarUrl": null,
"age": 18
}
]
let sortedArray = yourArray.sort((a, b) => {
// same value OR null on both sides
if (a.avatarUrl === b.avatarUrl) {
return 0;
}
else if (a.avatarUrl !== null) {
// the following part handles the fact that we can get two different URL which are not null
// you have to improve this part according to your needs
if(b.avatarUrl !== null){
return a.avatarUrl > b.avatarUrl ? -1 : 1; // the equality has already been handled on the first condition
}
return -1;
}
else {
return 1;
}
});
console.log(sortedArray);
它回傳這個:
[
{
id: 3,
avatarUrl: 'https://get-edu.kz/wp-content/uploads/2020/04/helpbox-contact.jpg',
age: 20
},
{ id: 1, avatarUrl: null, age: 20 },
{ id: 2, avatarUrl: null, age: 22 },
{ id: 4, avatarUrl: null, age: 18 }
]
如果您需要添加更多過濾器邏輯,您可以根據您的需要改進 sort 函式內部的代碼,但想法仍然相同:使用 sort 函式并實作它來對您的物件進行排序。
uj5u.com熱心網友回復:
我假設您需要按字母降序對空值進行排序,就像
我從這里提到的最后一個
let arr = [
{
"id": 1,
"avatarUrl": null,
"age": 20
},
{
"id": 2,
"avatarUrl": null,
"age": 22
},
{
"id": 3,
"avatarUrl": "https://get-edu.kz/wp-content/uploads/2020/04/helpbox-contact.jpg",
"age": 20
},
{
"id": 4,
"avatarUrl": null,
"age": 18
}
]
function compare(a, b) {
// equal items sort equally
if (a.avatarUrl === b.avatarUrl) {
return 0;
}
// nulls sort after anything else
else if (a.avatarUrl === null) {
return 1;
}
else if (b.avatarUrl === null) {
return -1;
}
};
arr.sort( compare );
console.log(arr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335765.html
標籤:有角的
