[英]Creating An Array of Objects From An Object Without Specific Key Values
Hello this is my first question on this platform so please feel free to remove or edit, or leave criticism.您好,这是我在这个平台上的第一个问题,所以请随时删除或编辑,或留下批评。
So I am parsing data from an API in react.所以我在反应中解析来自 API 的数据。 The data comes out looking something like this.
数据看起来像这样。
data = {
"20": "john",
"20.5": "jim",
"21": "bob",
"21.5": "james",
"22": "carl",
"23": "linda",
"25": "jack",
"25.5": "kyla",
"26": "jenny",
}
And I am trying to dynamically update a webpage using this data.我正在尝试使用这些数据动态更新网页。 I need to access the ages (keys) and the names (values).
我需要访问年龄(键)和名称(值)。
I am putting the object's key value pairs into an array so I can map them inline using array.map() , my code below.我将对象的键值对放入一个数组中,这样我就可以使用array.map()将它们内联 map ,我的代码如下。
var Array = []
for (const [key, value] of Object.entries(data)) {
Array.push({
age: key,
name: value,
});
}
Now this does for the most part what I am trying to do.现在,这在很大程度上完成了我正在尝试做的事情。 The output being a new array.
output 是一个新阵列。
[
{ age: '20', name: 'john' },
{ age: '21', name: 'bob' },
{ age: '22', name: 'carl' },
{ age: '23', name: 'linda' },
{ age: '25', name: 'jack' },
{ age: '26', name: 'jenny' },
{ age: '20.5', name: 'jim' },
{ age: '21.5', name: 'james' },
{ age: '25.5', name: 'kyla' }
]
Now the problem is that they are not in the same order as they were given.现在的问题是它们的顺序与给出的顺序不同。 For some reason the.5 ages all sorted at the end of the array.
由于某种原因,.5 个年龄都排在数组的末尾。 Is this a limitation of array.push() ?
这是array.push()的限制吗? Am I doing something fundamentally wrong with the Object.entries() function?
我对Object.entries() function 做错了什么吗? Or should I simply resort to using sorting methods once the array has been created?
还是应该在创建数组后简单地使用排序方法?
When iterating over objects, ascending whole number keys will always come first.迭代对象时,升序的整数键总是排在第一位。 The best approach to this sort of problem would be to change the backend so that it gives you the desired array of objects to begin with, instead of a somewhat broken format that you need to fix later.
解决此类问题的最佳方法是更改后端,以便它为您提供所需的对象数组,而不是您需要稍后修复的有点损坏的格式。
If that's not possible, you'll have to fix it client-side by taking all entries, then sorting them.如果这不可能,您必须在客户端通过获取所有条目,然后对其进行排序来修复它。
const input = { 20: 'john', 20.5: 'jim', 21: 'bob', 21.5: 'james', 22: 'carl', 23: 'linda', 25: 'jack', 25.5: 'kyla', 26: 'jenny' }; const result = Object.entries(input).map(([age, name]) => ({ age, name })).sort((a, b) => a.age - b.age); console.log(result);
You may also need to fix the API so that it gives you proper JSON, since您可能还需要修复 API 以便它为您提供正确的 JSON,因为
{
20: john
20.5: jim
is not valid syntax.不是有效的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.