使用javascript将对象转换为对象数组

时间:2019-05-06 19:55:36

标签: javascript arrays json

我想转换以下格式的对象:

{ From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} }

我想转换这个数组:

[
  {from: "A" ,to: "A1" , value: 1  },
  {from: "B" ,to: "B1" , value: 2},
  {from: "C"   ,to: "C1"   , value: 3  }
]

如何将其转换为javascript代码?

1 个答案:

答案 0 :(得分:1)

您提供的输入是错误的,因为它包含具有key:value对的数组和没有key:value的对象。应该是

{ From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }

现在要转换为所需的结果,可以使用map()

let obj = { From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }

let res = obj.From.map((form,i) => {
  let value = obj.value[i];
  let to = obj.To[i];
  return {form,to,value}
})
console.log(res)