首页 > 解决方案 > 如何将对象嵌套在对象中?

问题描述

我有一个生成以下对象的函数:

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
        }
    });

标签: javascriptreactjs

解决方案


您的意思是使用动态密钥吗?你可以试试:

const targetObject = {
  labels: {
    [this.props.templatename]: { ...currentObject.labels }
  }
};

const targetObject = {
  labels: {
    [this.props.templatename]: {
      x1: 'y1',
      x2: 'y2',
      x3: 'y3'
    }
  }
};

推荐阅读