Greetings, I hope you can help me, I need to relate an array united in a final object, my arrangements to relate are the following:
cabecera=['nombre', 'apellido'];
datos=['william', 'fernandez'];
I need to get an object that looks like this:
obetoFinal={
nombre:'william',
apellido:'fernandez'
}
I have tried many things but I can't get the result I need, so far I have done this but I get the error 'Parsing error: Unexpected token ['.
cabecera.forEach((c, i)=>{
let obj={
cabeceras[i] :datos[i]
}
})
There was little left to achieve your goal, you just have to make some corrections:
obj['nuevaPropiedad'] = 'valor'
, because, as you have it, in each iteration the entire object is overwritten and it would only have the last property.The short answer is
We create an empty object and then create its header name and data value fields.
For a more generic case, where there may be more than two elements
And now, to ensure that the data is consistent
you have 3 problems
That you think a declared
let
or local variable will live when it exits the function passed to theforEach
.You always override that variable.
If you want to add more data to your array it will become more complex, better use a loop
for
and using the arraydatos
instead of the arraycabecera
//Because you know the size of the arraycabecera
and there are not many elements.The solution is to declare the variable a outside of
forEach
and do:But if you want to expand the array
cabecera
so you don't have to manipulate the code you can do another loopfor
.Note: Neither of the two functions is error-proof, it may happen that you have less
datos
thancabecera
or vice versa.