如何按 angular 中的值对字典进行排序
how to sort a dictionary by value in angular
我正在使用字典并在其中插入值。
现在我想根据条件按值对字典进行排序。我该怎么做?
let dealCodes: Dictionary<string> = new Dictionary<string>();
dealCodes.AddUpdate(node.data.dealCode, node.data.dealCode)
字典结果如下:
items
A0zhr: "A"
A0zhw: "C"
A0zhz: "B"
看看这个例子。请记住它是伪代码,因为我不知道你的字典实现:
const dictionary = new Dictionary<string>();
const sortedKeys = Object.keys(dictionary).sort();
sortedKeys.forEach(elem=>{
console.log(dictionary[elem]) // yuo should see sorted output: A, B, C
})
除非你自己实现Dictionary,否则JS中的一般对象默认是按键排序。
您可以选择如下内容
组件
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
public originalData: {} = {
A0zhr: "A",
A0zhw: "C",
A0zhz: "B"
};
public sortedData = [];
name = "Angular " + VERSION.major;
ngOnInit(): void {
this.sortedData = [];
Object.keys(this.originalData)
.sort((a, b) => (this.originalData[a] > this.originalData[b] ? 1 : -1))
.map(x => {
console.log(x, this.originalData[x]);
this.sortedData.push([x, this.originalData[x]]);
});
}
}
HTML
<h3>Original Data</h3>
<ul>
<li *ngFor="let item of originalData | keyvalue">{{item.key}}::{{item.value}}</li>
</ul>
<h3>Sorted Data</h3>
<ul>
<li *ngFor="let item of sortedData">{{item[0]}}::{{item[1]}}</li>
</ul>
破解示例
我正在使用字典并在其中插入值。
现在我想根据条件按值对字典进行排序。我该怎么做?
let dealCodes: Dictionary<string> = new Dictionary<string>();
dealCodes.AddUpdate(node.data.dealCode, node.data.dealCode)
字典结果如下:
items
A0zhr: "A"
A0zhw: "C"
A0zhz: "B"
看看这个例子。请记住它是伪代码,因为我不知道你的字典实现:
const dictionary = new Dictionary<string>();
const sortedKeys = Object.keys(dictionary).sort();
sortedKeys.forEach(elem=>{
console.log(dictionary[elem]) // yuo should see sorted output: A, B, C
})
除非你自己实现Dictionary,否则JS中的一般对象默认是按键排序。
您可以选择如下内容
组件
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
public originalData: {} = {
A0zhr: "A",
A0zhw: "C",
A0zhz: "B"
};
public sortedData = [];
name = "Angular " + VERSION.major;
ngOnInit(): void {
this.sortedData = [];
Object.keys(this.originalData)
.sort((a, b) => (this.originalData[a] > this.originalData[b] ? 1 : -1))
.map(x => {
console.log(x, this.originalData[x]);
this.sortedData.push([x, this.originalData[x]]);
});
}
}
HTML
<h3>Original Data</h3>
<ul>
<li *ngFor="let item of originalData | keyvalue">{{item.key}}::{{item.value}}</li>
</ul>
<h3>Sorted Data</h3>
<ul>
<li *ngFor="let item of sortedData">{{item[0]}}::{{item[1]}}</li>
</ul>
破解示例