遍历 JSON 个父部分,测试操作然后返回负载

Iterating over JSON parent sections, testing for action and then returning payload

鉴于此 json 结构:

{
  users: [ { action: 'add', payload: [Array] } ],
  categories: [ { action: 'add', payload: [Array] } ],
  products: [ { action: 'add', payload: [Array] } ]
}

您将如何使用 .map()Object.keys 或类似的 ES6 优点来遍历每个节点(用户、类别、产品),然后获得“添加”操作(这样我就可以 if/then 到不同的操作)以及每个部分的有效载荷数组的内容?

如果您只对值感兴趣,可以使用 Object.values:

const data = {
  users: [ { action: 'add', payload: [Array] } ],
  categories: [ { action: 'add', payload: [Array] } ],
  products: [ { action: 'add', payload: [Array] } ]
};

Object.values(data).forEach(([{ action, payload}]) => // do anything with them);

如果您也需要密钥,请尝试 Object.entries:

Object.entries(data).forEach(([key, [{ action, payload}]]) => // same );