Change key name in JavaScript object

前端 未结 4 606
眼角桃花
眼角桃花 2020-12-10 13:25

I am checking the attributes in a JavaScript object, replacing some of the keys by deleting the prefix \"element\" and saving the new values in another object.



        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 13:48

    The problem is that you are looking for the property in the original object using the new key. Use keys[j] instead of key:

    var keys = Object.keys(json);
    for (var j=0; j < keys.length; j++) {
       var key = keys[j].replace(/^element_/, "");
       tmp[key] = json[keys[j]];
    }
    

    I uses a regular expression in the replace so that ^ can match the beginning of the string. That way it only replaces the string when it is a prefix, and doesn't turn for example noexample_data into no_data.

    Note: What you have is not "a json", it's a JavaScript object. JSON is a text format for representing data.

    Is that due to the fact that I converted the keys (Objects) to Strings (with the replace method)?

    No. The keys are strings, not objects.


    You could also change the properties in the original object by deleting the old ones and adding new:

    var keys = Object.keys(json);
    for (var j=0; j < keys.length; j++) {
       if (keys[j].indexOf("element_") == 0) {
         json[keys[j].substr(8)] = json[keys[j]];
         delete json[keys[j]];
       }
    }
    

提交回复
热议问题