javascript - 将对象转换为 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 中完全是新手,只有几天的工作时间......请在这个问题上帮助我
解决方案
尝试使用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()
使用这些键值对创建一个新对象。
推荐阅读
- javascript - 我们可以在 JS 文件的顶部写“use strict”,它会验证所有函数和语句吗?
- python - Django Migration InternalError 1054 未知列
- c - 使用 SAT 求解器打印 N-Queens 问题的所有解
- vue.js - 将 Axios 调用的结果添加到 State
- javascript - 带有数据表的嵌套表
- python - MySQL/python 字符集问题
- r - 从第三次观察开始,在 R 中进行黄土曲线拟合
- scala - 没有参数评估 zeppelin 中定义的 Scala 方法
- python - 如何基于单个列上的多个 StringMethods 有效且惯用地过滤 PandasDF 行?
- linux-kernel - 在 5.4 中编译 gpio-mockup