-1

Trying to arrange an array of objects to put in a table alphabetically whilst keeping a specific column as the first key/value pair in Javascript. It needs to stay as an array so I can map over it to render the table.

I've tried looping through the object and sorting it but cant seem to do it whilst keeping the 'category' as the first pair.

My data looks like this....

data = [{"Category": "Food",
        "Dave": "286 / 91% / 98%",
        "Caron": "215 / 83% / 87%",
        "Sam": "134 / 100% / 100%",
        "Edward": "433 / 100% / 100%",
        "Adam": "827 / 100% / 100%"},
        {"Category": "Drink",
        "Dave": "286 / 91% / 98%",
        "Elis": "215 / 83% / 87%",
        "Creed": "134 / 100% / 99%",
        "Edward": "433 / 100% / 100%",
        "Tanya": "87 / 100% / 10%"}]

I have arranged the header alphabetically but am now trying to align the table body

This seems to have done the job....

sortTableRows = obj => {
    const sortedObj = {};
    sortedObj["Category"] = "";
    Object.keys(obj)
      .slice(1)
      .sort()
      .forEach(key => {
        sortedObj[key] = obj[key];
      });
    return Object.keys(sortedObj);
  };
  • 1
    Show what have you tried. – Rafael Herscovici Sep 25 '19 at 14:32
  • Hi @markprwyatt please add the code that you have tried to your question. You say "I've tried looping through the object and sorting it but cant seem to do it whilst keeping the 'category' as the first pair." please include this code so we can help you out with it. – Cal Irvine Sep 25 '19 at 14:33

2 Answers2

0

Basically, If I understand you well you want to sort the objects in the array by key-value pairs. There is no direct way of performing the sorting but you can do it as here Sorting JavaScript Object by property value Then use the unshift to add the category at the beginning. So after the sorting, you do array.unshift() to add the category

more about unshift can be found here Unshift

harisu
  • 1,376
  • 8
  • 17
0

You could create new objects and assign the sorted key/value pairs to an object with a first key of Category.

var data = [{ Category: "Food", Dave: "286 / 91% / 98%", Caron: "215 / 83% / 87%", Sam: "134 / 100% / 100%", Edward: "433 / 100% / 100%", Adam: "827 / 100% / 100%" }, { Category: "Drink", Dave: "286 / 91% / 98%", Elis: "215 / 83% / 87%", Creed: "134 / 100% / 99%", Edward: "433 / 100% / 100%", Tanya: "87 / 100% / 10%" }];

data = data.map(o => Object.assign(
    { Category: null },
    ...Object
        .entries(o)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([k, v]) => ({ [k]: v }))
));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392