javascript - 如何从对象中获取无序的键数组

标签 javascript angular javascript-objects

我的 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>
结果将是一个对象数组,其顺序与 JSON 字符串中出现的顺序相同:

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/

相关文章:

javascript - xmlhttprequest(xhr) 对象 xhr.onerror 和 xhr.upload.onerror 的区别

javascript - 从 config.js AngularJS 中提取基本 url

Angular4/5 : how to create folder, 文本文件并使用 typescript 将数据写入该文件

javascript - 如何将对象与表行关联起来?

Javascript 两个 arraySort 返回相同的结果

javascript - 在对象内移动(而不是复制)属性 - 使用引用

javascript - 使用 javascript、范围输入和 css 转换的数学 : scale()

javascript - 基于原型(prototype)的语言

javascript - 故事书+字体文件

node.js - Angular 生产错误 : Property does not exist on type 'object'