I have a bothersome length of characters before all keys in this object. Since they are all the same, I would like to do a .map()
or forEach()
or some
You could use the new Object.fromEntries
along with Object.entries:
let remove = {
this: {
string: {}
}
}
remove.this.string.a = "apple"
remove.this.string.b = "banana"
remove.this.string.c = "carrot"
remove.this.string.d = "diakon"
console.log(remove.this.string)
let fixed = Object.fromEntries(
Object.entries(remove.this.string)
.map(([key, val]) => [key, val])
)
console.log(fixed)
Result:
{ a: 'apple', b: 'banana', c: 'carrot', d: 'diakon' }
Update:
For keys that are all one string:
let remove = {
'remove.this.string.a': 'apple',
'remove.this.string.b': 'banana',
'remove.this.string.c': 'carrot',
'remove.this.string.d': 'diakon'
}
let fixed = Object.fromEntries(
Object.entries(remove)
.map(([key, val]) => [key.replace('remove.this.string.', ''), val])
)
console.log(fixed)
Result:
{ a: 'apple', b: 'banana', c: 'carrot', d: 'diakon' }