0

I want to change the order of the key value pairs in an array (analyzeTableData) by another array (analyzeTableHeader).

const analyzeTableHeader = ["TermA", "TermC", "TermB"];
const analyzeTableData = [
{
   "TermA": "test1",
   "TermB": "test2",
   "TermC": "test3"
}, {
   "TermA": "test1a",
   "TermB": "test2a",
   "TermC": "test3a"
}];

I've tried to do it with sort and indexOf but It doesn't work.

analyzeTableData.sort(function (a, b) {
   return analyzeTableHeader.indexOf(a) - analyzeTableHeader.indexOf(b);
});

Expected Output:

const analyzeTableData = [
{
   "TermA": "test1",
   "TermC": "test3",
   "TermB": "test2"

}, {
   "TermA": "test1a",
   "TermC": "test3a",
   "TermB": "test2a"
}];

Thank you for your hints

mm1975
  • 1,583
  • 4
  • 30
  • 51
  • 2
    Can you show expected output? Im guessing Array.map would be useful. – JBallin Apr 25 '23 at 19:36
  • I've added the expected output – mm1975 Apr 25 '23 at 19:38
  • Are you aware that relying on object key order has some caveats? Are you open to other data structures? https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – JBallin Apr 25 '23 at 19:40
  • You can't change the order of properties in an object. See https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Barmar Apr 25 '23 at 19:40
  • `analyzeTableData.sort()` sorts the objects, not the properties in the array elements. – Barmar Apr 25 '23 at 19:41

1 Answers1

2

Order of keys in an object (items of analyzeTableData) doesn't make difference. As I understand (correct me please if I'm wrong), you'll print them out somewhere as the order of analyzeTableHeader. So you can use analyzeTableData as follows:

analyzeTableData.forEach(row => {
  analyzeTableHeader.forEach(col => {
    console.log(col, row[col] );
  });
});

and output will be ordered as below;

enter image description here

finally, you can make new Data from above code

const newAnalyzeTableData = [];
analyzeTableData.forEach(row => {
  let newRow = {};
  analyzeTableHeader.forEach(col => {
    newRow[col] = row[col];
  });
  newAnalyzeTableData.push(newRow);
});

console.log(JSON.stringify(newAnalyzeTableData, null, 4));

enter image description here

gdarcan
  • 595
  • 5
  • 8