Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda