JS展平数组

时间:2018-10-19 08:50:03

标签: javascript typescript

是否可以使JSON数组更平坦?

例如,我有这种JSON。如何将以{开头的对象合并为一个平面对象? “行”应转换为信息“名称”:“ Row1”

[
  [
    "Row1",
    {
      "TOI": 25116,
      "g": 8,
      "r_g": 0,
      "o_g": 0,
      "f_g": 0,
      "sg": 6
    }
  ]
]

这是我所期望的:

[
   {
      "name": "Row1",
      "TOI": 25116,
      "g": 8,
      "r_g": 0,
      "o_g": 0,
      "f_g": 0,
      "sg": 6
    }
]

1 个答案:

答案 0 :(得分:0)

解决问题的方法

let table = [
  [
    "Row1",
    {
      "TOI": 25116,
      "g": 8,
      "r_g": 0,
      "o_g": 0,
      "f_g": 0,
      "sg": 6
    }
  ], [
    "Row2",
    {
      "TOI": 25116,
      "g": 8,
      "r_g": 0,
      "o_g": 0,
      "f_g": 0,
      "sg": 6
    }
  ]
];

table = table.map(row => {
   return {
     "name": row[0],
     ...row[1]
   }
});

console.log(table);