我的 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": {...},
};
但我无权访问后端。我需要另一个解决方案。
<小时/>附注我从后端获取数据的方式
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>
该数组确实保证其值的顺序。
关于javascript - 如何从对象中获取无序的键数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49532411/