将对象重新排序为键的顺序与数组的顺序相同

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

我有一个看起来像这样的数组,

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

和一个对象数组,其中对象看起来像,

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

我想要做的是使上述对象和该数组中的任何其他对象与第一个数组中的值的顺序相匹配,因此完成的对象应该看起来像,

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

到目前为止我已经尝试了以下方法,

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

但是这个returns,

{[object Object]: undefined}

您可以通过在 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);

不是迭代行,而是迭代键 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)