[英]Sort by Object property and then append specific object to end of array within an Object of nested Arrays
我有以下帶有嵌套對象數組的對象。
我正在嘗試編寫一個簡單的 Javascript 函數,通過“label”屬性按字母順序對這些數組中的對象進行排序,然后將帶有“other”標簽的對象推送到該數組的末尾。
這是我當前的解決方案,但我想知道是否有更簡潔、更具聲明性的方法來處理此解決方案?
https://jsfiddle.net/3fjq50Lb/
let things = {
"animals": [{
"id": 0,
"label": "cat"
},
{
"id": 100,
"label": "Undefined"
},
{
"id": 200,
"label": "turtle"
},
{
"id": 300,
"label": "Other"
},
],
"colors": [{
"id": 0,
"label": "yellow"
},
{
"id": 100,
"label": "green"
},
{
"id": 200,
"label": "red"
},
{
"id": 300,
"label": "blue"
}
]
}
let sortedThings = {};
Object.entries(things).forEach((entry) => {
let key = entry[0];
let otherOption = entry[1].filter((o)=> o.label === "Other");
console.log(otherOption)
let vals = entry[1].sort((a, b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0)).filter((s) => s.label !== "Undefined")
if(otherOption.length){
vals = vals.filter((s) => s.label !== "Other");
vals = vals.concat(otherOption);
}
})
它可以優化如下:
const things = { "animals": [{ "id": 0, "label": "cat" }, { "id": 100, "label": "Undefined" }, { "id": 200, "label": "turtle" }, { "id": 300, "label": "Other" }, ], "colors": [{ "id": 0, "label": "yellow" }, { "id": 100, "label": "green" }, { "id": 200, "label": "red" }, { "id": 300, "label": "blue" } ] }; const sortedThings = Object.entries(things).reduce((obj, [key, value]) => (obj[key] = value .filter(item => item.label != "Undefined") .sort((a, b) => ( a = a.label.toLowerCase(), b = b.label.toLowerCase(), a == b ? 0 : b != "other" && (a == "other" || a > b) ? 1 : -1 )), obj ), {}); console.log(sortedThings);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.