javascript - 如何将对象嵌套在对象中?
问题描述
我有一个生成以下对象的函数:
const currentObject = {
labels: {
x1: "y1",
x2: "y2",
x3: "y3",
}
}
要在我的 api 中处理它,它应该具有如下格式:
const targetObject = {
labels: {
templatename:{
x1: "y1",
x2: "y2",
x3: "y3",
}
}
}
const templatename = this.props.templatename;
如何将对象嵌套在具有 const 模板名称的对象中?
我不想贴一堆代码,这两个对象只是一个例子,第一个可以通过以下函数生成:
state = {
"labels": {
}
}
onChange = (e, key) => {
this.setState({
labels: {
...this.state.labels,
[key]: e.target.value
}
});
解决方案
您的意思是使用动态密钥吗?你可以试试:
const targetObject = {
labels: {
[this.props.templatename]: { ...currentObject.labels }
}
};
const targetObject = {
labels: {
[this.props.templatename]: {
x1: 'y1',
x2: 'y2',
x3: 'y3'
}
}
};
推荐阅读
- android - 使用Moshi和retrofit2解析具有相同键但不同值的json字段
- reactjs - 在相同组件中识别单击的组件
- javascript - 将 CommonJS 默认导出导入为命名导出/无法加载 ES 模块
- python - 如何在 C# 中从 python 脚本异步读取数据
- ssh - 通过端口转发连接使用 ssh
- google-cloud-platform - 在没有角色/所有者的 GCP 上部署 Kubeflow 1.3
- javascript - ava 抛出 npm ERR!当 sinon 存根抛出新错误时测试失败
- java - java - 如何在Java中的Android Studio中比较具有相同JSON中相同键的JSON对象?
- r - 如何将此数据框写入excel(xlsx)?
- javascript - 合并2个html5画布的捕获视频流