Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Remove leading commas from keys in object

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 }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!