0

这基本上就是我的 API 中有效负载的样子。我想重塑数据,以便可以在前端动态显示数据,而无需对列名等内容进行硬编码。值得我使用 DRF、axios 和 react-redux。那就是说我想我只需要学习更多的香草js:/

*故意在 1 个条目与另一个条目中有不同数量的键。

data =[
{
    "id": 1,
    "j_column": {
        "name": "James",
        "outside_id": 1,
        "alt_name": "Jim",
        "full_name": "James the third"
    }
},
{
    "id": 3,
    "j_column": {
        "name": "Dennis",
        "outside_id": 57,
        "alt_name": "Denny",
        "full_name": "Dennis the third",
        "nickname": "Denny the super star"
    }
}]



newData =[
{
    "id": 1,
    "name": "James",
    "outside_id": 1,
    "alt_name": "Jim",
    "full_name": "James the third"
},
{
    "id": 3,
    "name": "Dennis",
    "outside_id": 57,
    "alt_name": "Denny",
    "full_name": "Dennis the third",
    "nickname": "Denny the super star"
}]
4

2 回答 2

0
var new_data = [];
data.map(item => {
    var obj = {};
    Object.keys(item).map(itemKey => {
        if (typeof item[itemKey] !== 'object') {
            obj[itemKey] = item[itemKey]
        }else
            Object.keys(item[itemKey]).map(subItemKey => {
                obj[subItemKey] = item[itemKey][subItemKey]
            })
    })
    new_data.push(obj);
})
console.log(new_data);
于 2020-09-03T23:14:03.747 回答
0

这是一种方法:

const data =[
  {
      "id": 1,
      "j_column": {
          "name": "James",
          "outside_id": 1,
          "alt_name": "Jim",
          "full_name": "James the third"
      }
  },
  {
      "id": 3,
      "j_column": {
          "name": "Dennis",
          "outside_id": 57,
          "alt_name": "Denny",
          "full_name": "Dennis the third",
          "nickname": "Denny the super star"
      }
}];

const newData = data.map((el) => {
  const obj = {...el.j_column};
  obj.id = el.id;
  return obj;
});

console.log(newData);

于 2020-09-03T22:37:22.533 回答