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

时间:2018-03-28 10:43:32

标签: 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指令在我的角度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": {...},
};

但我无法访问后端。我需要另一种解决方案。

P.S。我从后端获取数据的方式

  getData() {
    this._dataService.getList(this.name, this.age).subscribe(res => {
      this.list = JSON.parse(JSON.stringify(res));
      this.listKeys = Object.keys(this.list);
    });   
  }

2 个答案:

答案 0 :(得分:1)

根据定义,对象是无序的属性集合。作为解决方案,您可以使用数组而不是对象:

第一步是将响应从服务器转换为相同顺序的数组。

&#13;
&#13;
// 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);
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13; 结果将是一个对象数组,其顺序与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>

这个数组确实保证了它的值的顺序。

答案 1 :(得分:0)

这必然会有边缘情况,但是因为它起作用而添加它

如果您以JSON的形式从后端获取数据,那么您可以执行以下操作

注意:var json是占位符,因为您没有显示如何获取数据

var json = `{
    "6": {
        "id": 6,
        "name": "John",
        "age": 31
    },
    "42": {
        "id": 42,
        "name": "Alex",
        "age": 25
    },
    "3": {
        "id": 3,
        "name": "Tim",
        "age": 58
    }
}`;

var result = JSON.parse(json.replace(/\s?"(\d+)":/g, '"$1 ":'));
console.log(Object.keys(result));

同样,这肯定会失败,但我看不到任何其他方式你可以在客户端“修复”这个 - 我认为JSON.parse“reviver”函数会有所帮助,但它获得了3中的属性,6,42顺序 - 所以,根本没用;

相关问题