I need to replace different strings in an array of objects with empty values.
This is an example of one of the objects I have in my JSON response:
{
"data": [
{
"Section_B_Demographic_Details/formhub/uuid": "4f8640b7835742279e7058893957d633",
"Section_B_Demographic_Details/lugar_inscripcion": "mdhyh",
"Encuesta/Datos_Generales/nombre_apellido": "Juan Perez",
"Encuesta/Datos_Generales/tipo_up": "grupo_asociativo",
"Encuesta/Relevamiento/ESCALA_DE_PRODUCCI_N/nombre_up_emprend_negocio": "ConstruiMas",
"Encuesta/Relevamiento/ESCALA_DE_PRODUCCI_N/comienzo_activ_up": "2021-10-14",
"DEMANDA_P_BLICO_OBJETIVO/calle_up": "Soler",
"DEMANDA_P_BLICO_OBJETIVO/altura_up": "3919",
}
This information is repeated in each of the hundreds within the array. In order to replace all of them, they helped me with the following function:
const reemplazarStringNombreKey = (str, obj) => {
const newObj = {};
for(const propName in obj) {
const newPropName = propName.replace(str, '');
newObj[newPropName] = obj[propName];
}
return newObj;
}
Then, with a map to the array of objects:
const arrayObjNuevo = arrayObj.map(obj => reemplazarStringNombreKey(str, obj))
In this function, the string is one of the values that is repeated in all the objects.
const str = 'Section_B_Demographic_Details/';
If I had an array with the different values:
const arrayStr = ['Section_B_Demographic_Details/', 'Encuesta/Datos_Generales/nombre_apellido', ....etc];
How do I iterate over that array to replace all the values with the previously submitted function?
I tried the following way, and I can't find the replacement:
arrayStr.forEach(cadena => arrayObj.map(obj=>reemplazarStringNombreKey(cadena, obj)));
This is in order not to have, as I currently do, occupy multiple constants with the strings and then chain one map to another.
You could modify the current method that performs the replacement so that instead of a string it receives a list of strings. That way in a single call you can achieve the task.
To do this, we will rely on the Array type method
find
, which returns the first element of the list that meets the condition. In this case, the condition is set using theincludes
String method. We want the list to return the string that is part of the name of the property we are iterating over. If the property name includes the list string, this string is returned and then replaced in the property name. This way, in a single call, you pass the list of strings you want to replace and the object. If the object does not contain any of the elements in the list among its attribute names, we set the value returned byfind
to an empty string. If the list contains strings that are not included in the attribute name, nothing is replaced.For example:
As can be seen in the code above, the list of strings to replace contains 3 elements, of which only 2 are part of an attribute name. Only those that are in the list and that are part of the name are replaced.
I hope this helps you solve the problem.