我的 js 中有来自后端的数据,如下所示:
var list = {
"6": {
"id": 6,
"name": "John",
"age": 31
},
"42": {
"id": 42,
"name": "Alex",
"age": 25
},
"3": {
"id": 3,
"name": "Tim",
"age": 58
},
};
然后我需要通过 ngFor 指令在我的 angular html 模板中显示这些数据。但首先我必须获得一组对象键:
var listKeys= Object.keys(list);
接下来我可以在模板中输出数据:
<div *ngFor="let item of listKeys">
<p>{{list[item].id}}</p>
<p>{{list[item].name}}</p>
<p>{{list[item].age}}</p>
<hr>
</div>
但问题是我的数据顺序发生了变化。我在 listKeys 下一个数组 ["3", "6", "42"] 中有。但我想在那个 ["6", "42", "3"] 中有原始顺序。我发现的解决方案之一是将键设为非数字字符串。例如:
var list = {
"+6": {...},
"+42": {...},
"+3": {...},
};
但我无权访问后端。我需要另一个解决方案。
PS 我从后端获取数据的方式
getData() {
this._dataService.getList(this.name, this.age).subscribe(res => {
this.list = JSON.parse(JSON.stringify(res));
this.listKeys = Object.keys(this.list);
});
}
根据定义,对象是无序的属性集合。作为解决方案,您可以使用数组而不是对象:
第一步是以相同的顺序将来自服务器的响应转换为数组。
// Original JSON string received from API
var jsonString = `{
"6": {
"id": 6,
"name": "John",
"age": 31
},
"42": {
"id": 42,
"name": "Alex",
"age": 25
},
"3": {
"id": 3,
"name": "Tim",
"age": 58
}
}`;
// Array of ordered id's
const orderedIds = [];
// Find all id's in the JSON string and push them to the array
const pattern = /"?id"?\: (\d*)/g;
let match;
while (match = pattern.exec(jsonString)) {
orderedIds.push(parseInt(match[1]));
}
// parse the original JSON object
const originalList = JSON.parse(jsonString);
// resulting ordered Array
const result = [];
// Push the object in the array by order
for(x of orderedIds) {
result.push(originalList[x]);
}
// Log the resulting array
document.getElementById("result").innerText = JSON.stringify(result);
<pre id="result"></pre>
result = [
{
"id": 6,
"name": "John",
"age": 31
},
{
"id": 42,
"name": "Alex",
"age": 25
},
{
"id": 3,
"name": "Tim",
"age": 58
},
];
在此之后,您可以在模板中使用它:
<div *ngFor="let item of result">
<p>{{item.id}}</p>
<p>{{item.name}}</p>
<p>{{item.age}}</p>
<hr>
</div>
这个数组确实保证了它的值的顺序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句