As far as I know these days, there is no native way to do this in JS.
What can be done is to create an auxiliary function that creates a property with a value in passed objects as argument for that function:
function inserePropriedadeComValorNoObjeto(objeto, propriedade, valor) {
objeto[propriedade] = valor;
}
From this, you can call the function by passing what you need in a repeat loop forEach
in an array, just as an example:
arrayDeObjetos.forEach(objeto => {
inserePropriedadeComValorNoObjeto(objeto, 'redirection', 'valor')
})
It is also possible to change forEach
for map
and return a new object array with the properties you want, just return the function object inserePropriedade...
after inserting the property, such as return objeto
at the end of it:
const novoArrayDeObjetosComPropriedadeRedirection = arrayDeObjetos.map(objeto => inserePropriedadeComValorNoObjeto(objeto, 'redirection', 'valor'))
Your function would be:
function inserePropriedadeComValorNoObjeto(objeto, propriedade, valor) {
objeto[propriedade] = valor;
return objeto;
}
If you prefer, you can call the function for each object manually without using the return
. The function will insert a property into the object you passed as argument, changing it by reference.
I hope I’ve helped in some way.
Got it bro. Very well explained. Congratulations on the knowledge.
– PiviaN