Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda