'How to transfer content of object of objects into array of objects and order it

Given the following object

data = {
 "c": {name: "c"},
 "2": {name: "two"},
 "1": {name: "one"},
 "a": {name: "a"}
}

It should end in an array with the following order

 [
 {name: "a"},
 {name: "c"},
 {name: "one"},
 {name: "two"}
 ]

How can I do so?

Because if I do

let newArr = []

for (let i in data){newArr.push(data[i])}

It ends up as

 [ 
 {name: "one"},
 {name: "two"},
 {name: "a"},
 {name: "c"}
 ]


Solution 1:[1]

Logic.

  • Sort the keys in your required format. Alphabets first, numbers last.
  • Return the data from your array based on this sorted keys.

Working Fiddle

const data = {
  "c": { name: "c" },
  "2": { name: "two" },
  "1": { name: "one" },
  "a": { name: "a" }
}
const sortedKeys = Object.keys(data).sort().sort((a, b) => {
  if ((isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b))) { // Both are same type
    return a < b;
  } else { // a nad b are of different types
    return -1;
  }
});

const output = sortedKeys.map((key) => data[key]);
console.log(output);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nitheesh