首页 > 解决方案 > 将对象数组转换为表格格式的数据

问题描述

我有以下对象数组:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut",
    "completed": false
  }
]

我想要以下作为输出:

userId | id | title       | completed |
  1    | 1  | delectus aut| false     |
  1    | 2  | quis ut     | false     |

我尝试过使用lodash,但考虑到循环的数量,我觉得我们有比这更好的解决方案:

jsonObject = response; // consider the above mention object here.  
keys = _.keys(json[0]); 

在这里,我发现json[0]并非在所有情况下都相同,那么找到解决方案的最佳方法是什么。

任何帮助将不胜感激!!!

标签: jsonreactjslodash

解决方案


受@Akrion 解决方案的启发,这里是修改后的版本。

有点冗长的解决方案,但这将对您有所帮助:

  1. 您的 JSON 数据中有不同的键
  2. 您在对象中有不同的键序列
  3. 想要在数据不可用的情况下设置默认值

const json = [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut",
    "completed": true
  },
  {
    "completed": false,
    "userId": 1,
    "title": "quis ut",
    "id": 2,
    "extraProp": "test"
  },
];

const headers = Array.from(new Set(json.reduce((acc, cur) =>
  [...acc, ...Object.keys(cur)], [])));

const data = [headers];
const defaultValue = 'NA';

json.forEach(item => {
  data.push(headers.reduce((acc, header) =>
    acc.push(item.hasOwnProperty(header) ? item[header] : defaultValue) && acc, []));
});
console.log(data);

Stackblitz 链接:https ://stackblitz.com/edit/js-zyh1ps


推荐阅读