如何在对象中设置键名和文件名相同?

下面是对象,我的要求是,文件名和它的值应该相同。我们怎么能做到这一点?


const obj = {

  email: this.formUser.value.email,

  phoneNumber: this.formUser.value.mobile,

  profileImageName: file,

  fileObj: {

    // want the same logo.png to be the key name here

    file: {

      fileName: file, //value is logo.png

      fileDescription: this.formUser.value.fileDescription

    }

  }

}


慕仙森
浏览 57回答 1
1回答

慕桂英3389331

[]可用于将计算值定义为 JSON 对象中的属性名称。有关更多信息,请参阅此处下面是一个相同的例子let myKey = "logo.png" let val = "Logo.png"var obj = {  [myKey]: val,}console.log(obj)所以在你的情况下,这可以像下面这样完成 const obj = {      email: this.formUser.value.email,      phoneNumber: this.formUser.value.mobile,      profileImageName: file,      [file]: {// using [] will allow to use dynamic key names in json obj        file: {          fileName: file, //value is logo.png          fileDescription: this.formUser.value.fileDescription        }      }    };希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript