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

148
Vistas
What is the efficient way to shallow clone an object using JavaScript?
//function for creating a shallow object and remove the multiple spaces
export const getTrimmedValues = (values) => {
  const shallowValues = {
    ...values,
  };
  for (const key in shallowValues.primaryInformation) {
    const currentValue = shallowValues.primaryInformation[key];
    if (typeof currentValue === 'string') {
      shallowValues.primaryInformation[key] = currentValue.replace(/\s+/g, ' ').trim();
    }
  }
  return shallowValues;
};


//Original Object
const values = {
    otherObject: {}
    otherArray: []
    primaryInformation: {
        email: "test.test@testdata.com"
        externalId: "DSB-External test"
        firstName: "Dave External test    test"
        isGood: true
        isHeaven: false
        lastName: "Bacay External"
        userId: 656555
    }
}

//calling the function
getTrimmedValues(values)

I want to create a shallow object from the original object and edit the string to remove the multiple spaces by using shallow object and for loop, I think I implemented it in a wrong way.

All advices and comments are appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here we can take advantage of JSON.stringify function has a second parameter as a replacer function is internally iterating on every key of object. Please check the below code.

//Original Object
const values = {
  otherObject: {},
  otherArray: [],
  primaryInformation: {
      email: "dave.external@testdata.com",
      externalEmployeeId: "DSB-External test   ",
      firstName: "Dave External test    test",
      isActive: true,
      isExternal: false,
      lastName: "Bacay External",
      userId: 656555,
  }
};

function getTrimmedValues(obj) {
  let str = JSON.stringify(obj, (key, value) => {
    if(typeof value === 'string') {
      return value.replace(/\s+/g, ' ').trim()
    }
    return value;
  });
  return JSON.parse(str);
}
console.log(getTrimmedValues(values));

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