简体   繁体   中英

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. 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.

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.

[
  { 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. Is this a limitation of array.push() ? Am I doing something fundamentally wrong with the 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

{
      20: john
      20.5: jim

is not valid syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM