'How to rename iterably object properties
Every Object properties have underscored the first letter; I wanna delete this first substring, and try the string method "replace" to all object properties, but it's not working in this case.
// nested object
const posts = {
// ...
'post-meta-fields': {
_bg_advantages_home: [''],
_bg_banner_home: ['35'],
_bg_info_1_home: ['41'],
_bg_info_2_home: [''],
_bg_offers_home: ['38'],
_bg_sales_home: ['36'],
_bg_video_home: ['']
}
// ...
};
// I tried this, but its not working
for (const key in posts['post-meta-fields']) {
for (let key_2 in key) {
key_2 = key_2.replace('_', '');
}
}
Solution 1:[1]
Maybe you can do something like this,
const tempObj = {};
for(let key in posts["post-meta-fields"]) {
const modifiedKey = key.replace('_','');
tempObj[modifiedKey] = posts["post-meta-fields"][key]
}
posts["post-meta-fields"] = tempObj;
Hope you got some idea!
Solution 2:[2]
Now you just need to delete the old key and add the new key:
let newKey = key_2.replace('_','');
key.newKey = key[key_2];
delete key[key_2];
Solution 3:[3]
You can create a new key with the modified name and add the appropriate values to it and then delete the old key with the underscore . Without using any extra space Time complexity : O(n) Space complexity : O(1)
// nested object
const posts = {
// ...
'post-meta-fields': {
_bg_advantages_home: [''],
_bg_banner_home: ['35'],
_bg_info_1_home: ['41'],
_bg_info_2_home: [''],
_bg_offers_home: ['38'],
_bg_sales_home: ['36'],
_bg_video_home: ['']
}
// ...
};
// I tried this, and it is working
for (const key in posts['post-meta-fields']) {
let newKey = key.replace("_","");
posts['post-meta-fields'][newKey] = posts['post-meta-fields'][key];
delete posts['post-meta-fields'][key];
}
console.log(posts);
// nested object
const posts = {
// ...
'post-meta-fields': {
_bg_advantages_home: [''],
_bg_banner_home: ['35'],
_bg_info_1_home: ['41'],
_bg_info_2_home: [''],
_bg_offers_home: ['38'],
_bg_sales_home: ['36'],
_bg_video_home: ['']
}
// ...
};
// I tried this, and it is working
for (const key in posts['post-meta-fields']) {
let newKey = key.replace("_","");
posts['post-meta-fields'][newKey] = posts['post-meta-fields'][key];
delete posts['post-meta-fields'][key];
}
console.log(posts);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shri Hari L |
Solution 2 | user835611 |
Solution 3 | Hritik Sharma |