//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) Quiero crear un objeto poco profundo a partir del objeto original y editar la cadena para eliminar los espacios múltiples usando un objeto poco profundo y un bucle for , creo que lo implementé de manera incorrecta.
Todos los consejos y comentarios son apreciados.
Aquí podemos aprovechar que la función JSON.stringify tiene un segundo parámetro, ya que una función de reemplazo itera internamente en cada clave del objeto. Por favor, compruebe el siguiente código.
//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));