'Reordering an object to the keys are in the same order as an array

I have an array that looks like this,

['event_tag', 'workflow_tag', 'created_timestamp', 'success']

and an array of objects where the object looks like,

{
    "created_timestamp": "2022-04-01T13:14:53.028002Z",
    "workflow_tag": "dj807",
    "event_tag": "refresh",
    "success": true
}

What I am wanting to do is make the above object and any other objects in that array match the order of the values in the first array so the finished object should look like,

{
    "event_tag": "refresh",
    "workflow_tag": "dj807",
    "created_timestamp": "2022-04-01T13:14:53.028002Z",
    "success": true
}

I have tried the following so far,

const keys = ['event_tag', 'workflow_tag', 'created_timestamp', 'success'];
newRowData = parsedRows.reduce((obj, v) => {
    obj[v] = keys[v];
    return obj
}, {});

But this returns,

{[object Object]: undefined}


Solution 1:[1]

You could order the keys by constructing a new object inside of an Array#map:

const parsedRows = [ { a: 1, c: 3, d: 4, b: 2, }, { b: 6, a: 5, c: 7, d: 8, }, { d: 12, b: 10, a: 9, c: 11, }, ];
const order = ['a', 'b', 'c', 'd'];

let newData = parsedRows.map(row => {
  let newRow = {};
  for (let key of order) {
    newRow[key] = row[key];
  }
  return newRow;
});

console.log(newData);

Solution 2:[2]

Instead of iterating over Rows, Iterate on keys either map/reduce.

const keys = ["event_tag", "workflow_tag", "created_timestamp", "success"];

const obj = {
  created_timestamp: "2022-04-01T13:14:53.028002Z",
  workflow_tag: "dj807",
  event_tag: "refresh",
  success: true,
};

const res = Object.assign({}, ...keys.map((key) => ({ [key]: obj[key] })));

console.log(res)

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 lejlun
Solution 2 Siva K V