[英]How do you access a single property in an array of objects in Angular 6 typescript?
[英]How do you sort an array of objects by a given property in Typescript?
假設您有以下類型的對象數組:
type Obj = {
id: number,
created: Date,
title: string
}
你如何在不被類型系統絆倒的情況下按給定的屬性排序? 例如:
const numberSorted = objArray.sortBy("id");
const dateSorted = objArray.sortBy("created");
const stringSorted = objArray.sortBy("title");
您可以使用Array.prototype.sort
例如:
objArray.sort((a, b) => {
// Some code for comparison
});
了解有關排序 function 的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
你可以定義一個 function 像
function sortByProperty<T, V>(
array: T[],
valueExtractor: (t: T) => V,
comparator?: (a: V, b: V) => number) {
// note: this is a flawed default, there should be a case for equality
// which should result in 0 for example
const c = comparator ?? ((a, b) => a > b ? 1 : -1)
return array.sort((a, b) => c(valueExtractor(a), valueExtractor(b)))
}
然后可以像這樣使用
interface Type { a: string, b: number, c: Date }
const arr: Type[] = [
{ a: '1', b: 1, c: new Date(3) },
{ a: '3', b: 2, c: new Date(2) },
{ a: '2', b: 3, c: new Date(1) },
]
const sortedA: T[] = sortByProperty(arr, t => t.a)
const sortedC: T[] = sortByProperty(arr, t => t.c)
// or if you need a different comparison
const sortedX: T[] = sortByProperty(arr, t => t.c, (a, b) => a.getDay() - b.getDay())
這也適用於對象t => tabc
中的嵌套屬性,或者適用於需要進一步派生排序鍵的情況,例如t => tatoLowerCase()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.