I'm trying to remove all existing square brackets from the entries
keys in the following array of objects:
data: [
{title: "Title1", entries: { 'Entry1': 333333, '[ABC]Entry2': 1234, 'Entry3': 5555 }},
{title: "Title2", entries: { '[ABC]Entry1': 5555, 'Entry2': 4444,'Entry3': 2222 }}
]
My goal is to have ABCEntry2
and ABCEntry1
instead of [ABC]Entry2
and [ABC]Entry1
.
For that, I've mapped through the data
, then mapped through the Object.keys
of x.entries
within in, checked if there's any bracket existing in the key, and, if so, replaced it with ''
.
Here is the code:
data.map(x => {
Object.keys(x.entries).map( y => {
if(y.includes('[') && y.includes(']')) {
y = y.replace(/\[/g, '').replace(/]/g, '');
console.log("I have no brackets: ", y);
}
})
console.log("I still have brackets: ", x.entries);
})
console.log("I have brackets here too: ", data);
If I print the y
value, I can see the desired result with no square brackets. However, I lose it if I try to print/use it outside of the Object.keys(x.entries)
mapping. Instead, I am getting the original data with the square brackets again.
I wonder if there is a way to have my updates on x.entries
and entire data
without creating a new variable and storing the changes there? So that when I print data
, it shows the updated entries with no square brackets in its keys?
CodePudding user response:
Changing y
inside the callback doesn't mutate the original object. You can map the key to a new key and then construct a new object from the mapped entries instead.
const data=[{title:"Title1",entries:{'Entry1':333333,'[ABC]Entry2':1234,'Entry3':5555}},{title:"Title2",entries:{'[ABC]Entry1':5555,'Entry2':4444,'Entry3':2222}}];
const newData = data.map((object) => ({
...object,
entries: Object.fromEntries(Object.entries(object.entries)
.map(([key, value]) => [
key.replace(/\[/g, "").replace(/\]/g, ""),
value,
])),
}));
console.log(newData);
For a solution that mutates the original data
array, you need to loop over the keys, get a new key, then delete the old key while assigning the new one.
const data=[{title:"Title1",entries:{'Entry1':333333,'[ABC]Entry2':1234,'Entry3':5555}},{title:"Title2",entries:{'[ABC]Entry1':5555,'Entry2':4444,'Entry3':2222}}];
data.forEach((object) => {
for (const key in object.entries) {
const newKey = key.replace(/\[/g, "").replace(/\]/g, "");
const value = object.entries[key];
delete object.entries[key];
object.entries[newKey] = value;
}
});
console.log(data);