Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  113] [ 5]  / answers: 1 / hits: 48163  / 9 Years ago, tue, september 8, 2015, 12:00:00

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.



var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
key = keys[j].replace(element_, );
switch(key) {
default :
tmp[key] = json[key];
break;
}
}


The matter is that when I do that, I can log all the keys, they have the correct names, but when I try to set the values associated to these keys, they are undefined (json[key]).



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


More From » javascript

 Answers
58

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

[#65149] Saturday, September 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hakeemabramh

Total Points: 234
Total Questions: 109
Total Answers: 109

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;