【问题标题】:How to rename the existing object's key using java-script /Angular? [duplicate]如何使用 javascript /Angular 重命名现有对象键? [复制]
【发布时间】:2020-01-17 22:32:00
【问题描述】:

我有一个现有的对象,

this.data = {
   "part": "aircraft",
   "subid": "wing",
   "information.data.keyword": "test",
   "fuel.keyword": "lt(6)"
}

我要做的是检查每个key,如果密钥有.keyword,那么我试图删除它并在没有.keyword 的情况下创建它。我不确定如何重命名和推送到现有对象。

到目前为止我尝试过的,

for(let x in this.data) {      
    if(x.includes('.keyword')) {      
        let xy = x.replace(/.keyword/g, "");
        console.log(xy);
    }
}

【问题讨论】:

标签: javascript angular object


【解决方案1】:

您可以尝试复制/克隆对象,将其添加到 this.data,然后使用 .keyword 删除版本。

【讨论】:

    【解决方案2】:

    首先您需要创建一个新密钥。为新创建的键分配值后,您需要删除旧键。

    试试这个:

     this.data = {
        "part": "aircraft",
        "subid": "wing",
        "information.data.keyword": "test",
        "fuel.keyword": "lt(6)"
      }
      for (let x in this.data) {
        if (x.includes('.keyword')) {
          this.data[x.replace(/.keyword/g, "")] = this.data[x];
          delete this.data[x];
        }
      }
      console.log(this.data)

    【讨论】:

      【解决方案3】:

      试试这个

       let data = {
          "part": "aircraft",
          "subid": "wing",
          "information.data.keyword": "test",
          "fuel.keyword": "lt(6)"
        }
      
        Object.keys(data).forEach((x) => {
          if (x.includes('.keyword')) {
      
            this.data[x.replace(/.keyword/g, "")] = data[x];
            delete data[x]
          }
      });
      
      console.log(data)
      

      【讨论】:

        【解决方案4】:

        您已经使用过includes()replace()。只需要使用@Andreas 提到的delete 运算符删除对象并创建新条目。

        for(var k in data) {
           if (k.includes(".keyword")) {
              var newKey =  k.replace(/.keyword/g, "");// New key for new entry without .keyword
              data[newKey] = data[k]; //Creating new entry 
              delete(data[k]); //Deleting old entry
           }
        }
        

        【讨论】:

          猜你喜欢
          • 2021-08-16
          • 2011-06-06
          • 1970-01-01
          • 2019-12-22
          • 2020-10-14
          • 2015-05-14
          • 1970-01-01
          • 2023-02-25
          • 2019-10-31
          相关资源
          最近更新 更多