-1

I wanna sort object fields for iterated array index. For example:

const data = {
                "all": 2,
                "test1": 0,
                "test": 2,
                "test2": 0,
                "test3": 0,
                "test4": 0,
                "test5": 0
            };
const users = [ "test","test1","test2","test3","test4","test5"];

I wanna data object like this:

data = {
                    "all": 2,
                    "test": 2,
                    "test1": 0,
                    "test2": 0,
                    "test3": 0,
                    "test4": 0,
                    "test5": 0
}

How can i achieve this?

2 Answers2

0

You can sort the entries of the object based on the index of the key in the array.

const data = {
  "all": 2,
  "test1": 0,
  "test": 2,
  "test2": 0,
  "test3": 0,
  "test4": 0,
  "test5": 0
};
const users = ["test", "test1", "test2", "test3", "test4", "test5"];
let res = Object.fromEntries(Object.entries(data).sort(([k1], [k2]) => 
            users.indexOf(k1) - users.indexOf(k2)));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

A similar question has been answered here.

const data = {
  "all": 2,
  "test1": 0,
  "test": 2,
  "test2": 0,
  "test3": 0,
  "test4": 0,
  "test5": 0
};

const sortable = Object.entries(data).sort(([,a],[,b]) => b-a).reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);
Eesa
  • 54
  • 5