Struggling to figure out how to remove leading commas from an keys in my object, so for example given this object:
{ 'D,F,': 14, 'G,,E': 32, ',D,R': 24 }
This is my desired end result
{ 'D,F,': 14, 'G,,E': 32, 'D,R': 24 }
Here is what I have tried
const newArr = JSON.parse(
JSON.stringify(sample).replaceAll('C', '').replaceAll(/(^[,\s]+)/g, '')
)
console.log(newArr)
and what I am getting
{ 'D,F,': 14, 'G,,E': 32, ',D,R': 24 }
If your environment allows it you should use Object.entries and its opposite Object.fromEntries:
const sample = { 'D,F,': 14, 'G,,E': 32, ',D,R': 24 };
const transformed = Object.fromEntries(
Object.entries(sample).map(([key, value]) => [key.replace(/^,+/, ""), value])
);
console.log(transformed);
From MDN's page about Object.entries and Object.fromEntries:
The
Object.entries()method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
The
Object.fromEntries()method transforms a list of key-value pairs into an object.
After we get our pairs, we take each pair and remove the leading comma if any with replace, then take the transformed pairs and turn it back into an object.
You can also use forEach to loop through all elements and find if any key is beginning with a comma.
let json = { 'D,F,': 14, 'G,,E': 32, ',D,R': 24 };
let arr = []
Object.entries(json).forEach((element) => {
if(element[0].charAt(0) == ','){
let newKey = element[0].substring(1);
arr[newKey] = element[1];
}else {
arr[element[0]] = element[1];
}
});
let newJson = JSON.parse(JSON.stringify({ ...arr }));
console.log(newJson);