首页 > 解决方案 > 将对象转换为 JSON

问题描述

我正在尝试将下一个变量转换为 JSON

class RHypervisor extends React.Component {
  constructor(props) {
    super(props);

    this.label = "hv01"

    this.state = {
      hypervisor_type: "xen",
      cpu_units: 2250,
      hypervisor_group_label: "kvm_hvz_1",
      hardware_configs: {
        vsphere: {}
    }
  }
}

var myMap = new Map().set(this.label, this.state)

console.log(myMap)

代码工作正常,但我无法获得我需要的 JSON,格式如下:

{
   "hv01": {
      "cpu_units": "2250",
      "hypervisor_group_label": "kvm_hvz_1",
      "hardware_configs": {
        "vsphere": {...}
      }
   }
}

我进入控制台:

[
  "hv01",
    {
      "hypervisor_type": "xen",
      "cpu_units": 2250,
      "hypervisor_group_label": "kvm_hvz_1",
      "hardware_configs": {
        "vsphere": {...}
      }
    }
  }
]

我如何获得顶级密钥this.label和下一个对象this.state

PS。我在 JS 中完全是新手,只有几天的工作时间......请在这个问题上帮助我

标签: javascriptdictionary

解决方案


尝试使用Map.entries()Object.fromEntries()

const myMap = new Map();
myMap.set("hv01", {
  hypervisor_type: "xen",
  cpu_units: 2250,
  hypervisor_group_label: "kvm_hvz_1",
  hardware_configs: {
    vsphere: {}
  }
});

console.log(Object.fromEntries([...myMap.entries()]));

解释:

[...myMap.entries()]返回一个键值对数组 ( [["hv01", { ... }]]) 并Object.fromEntries()使用这些键值对创建一个新对象。


推荐阅读