0

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}
Udders
  • 6,914
  • 24
  • 102
  • 194
  • 1
    Objects are usually seen as an unordered collection of key/value pairs. Trying to order them often doesn't make much sense and number-like keys can't be custom ordered (number-like keys will always be first and in ascending order). Why exactly do you need to order them? – Ivar Apr 12 '22 at 11:08
  • I have a table component that takes a columns props (the array of values) and rowData prop (the array of objects) currently the row data doesn't match match up with column headings. i.e timestamp is actually labelled as event_tag in the table. – Udders Apr 12 '22 at 11:14
  • Does this answer your question? [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – lejlun Apr 12 '22 at 11:52
  • That just sorts the keys alphabetically right? I am wanting a specific order. – Udders Apr 12 '22 at 11:55
  • It sound like you want to `map` over the `parsedRows`, and then for each row *`reduce` the `keys`* to an object with the values from the row. – Bergi Apr 15 '22 at 22:49

2 Answers2

0

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);
lejlun
  • 4,140
  • 2
  • 15
  • 31
0

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)
Siva K V
  • 10,561
  • 2
  • 16
  • 29