I have an array:
funciones = ['paciente.hospital', 'paciente.enfermad', 'paciente.documento'];
and a string:
const parametro = '72476675';
What I want to do is create a dynamic object from this array and this string so that it looks like this:
const result = {
exp: 'paciente.hospitap',
params: {
exp: 'paciente.enfermedad',
params: {
exp: 'paciente.documento',
params: parametro,
}
},
};
where the last function element will receive the parameter which is the string.
const result = {};
funciones.forEach((fn, i) => {
if (i === funciones.length - 1) { // si es el ultimo le asignamos el parametro
result.exp = parametro
} else {
// aqui no se como ir acumulando el objeto
console.log(fn);
}
});
The problem is that I don't know how to accumulate the object since this array of functions can have less or more elements.
Using
.reduceRigth
it could be solved:The idea would be to iterate from the right, and add the current object into a new object, the other case being the first time, an where we add
parametro
.Using
array.reduce
you could get such a result.By iterating the array:
- We create the properties
exp
andparams
for the objectacc
.- If it is the last value instead of assigning a
{}
toparams
, we assignparámetro
.Example: