I have two arrays, one that contains my data and the other that contains the new keys of my array, where I have the index field, which refers to the index of the other array where I want to modify the key.
I have been trying to do it as follows but I couldn't get what I want
var claves = [{c_camp: "c_prod",index: 0},
{c_camp: "l_prod",index: 1},
{c_camp: "k_medi",index: 5},
{c_camp: "s_pre1",index: 2}]
var datos = [ {
"0":"0000001",
"1":"WANTAN FRITO",
"2":"8,00",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{
"0":"0000002",
"1":"ROLL DE ESPÁRRAGOS",
"2":"10,00",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{"0":"0000003",
"1":"ROLL PRIMAVERA",
"2":"10,00",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{
"0":"0000004",
"1":"ALITAS BROASTER",
"2":"6,50",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{
"0":"0000005",
"1":"NABO ENCURTIDO",
"2":"5,00",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{
"0":"0000006",
"1":"SALCHIPAPA TUSAN",
"2":"15,00",
"3":"DIM SUM",
"4":"FRITOS",
"5":"001\r"
},
{
"0":"0000007",
"1":"SOPA WANTAN",
"2":"9,50",
"3":"SOPAS",
"4":"SOPAS",
"5":"001\r"
}]
var resp = []
datos.forEach( function(valor1, indice1, array1){
claves.forEach( function(valor2, indice2, array2){
resp.push({[valor2.c_camp]:valor1[indice2]})
})
})
console.log(resp);
what I want to get is as follows:
[ {
"c_prod":"0000001",
"l_prod":"WANTAN FRITO",
"s_pre1":"8,00",
"k_medi":"001\r"
},
{
"c_prod":"0000002",
"l_prod":"ROLL DE ESPÁRRAGOS",
"s_pre1":"10,00",
"k_medi":"001\r"
},
{"c_prod":"0000003",
"l_prod":"ROLL PRIMAVERA",
"s_pre1":"10,00",
"k_medi":"001\r"
},
{
"c_prod":"0000004",
"l_prod":"ALITAS BROASTER",
"s_pre1":"6,50",
"k_medi":"001\r"
},
{
"c_prod":"0000005",
"l_prod":"NABO ENCURTIDO",
"s_pre1":"5,00",
"k_medi":"001\r"
},
{
"c_prod":"0000006",
"l_prod":"SALCHIPAPA TUSAN",
"s_pre1":"15,00",
"k_medi":"001\r"
},
{
"c_prod":"0000007",
"l_prod":"SOPA WANTAN",
"s_pre1":"9,50",
"k_medi":"001\r"
}]
Thank you very much in advance, and I hope you can help me ---------------------------------------- ------------- ------------------------------------- ---------------- ---------------------------------- ------------------------------------------------- _ ---------------------- ---------------------------- ------------------------- ------------------------- ---------------------------- ---------------------- ------------------------------- ------------------- ---------------------------------- ---------------- ------------------------------------- ------------- ---------------------------------------- ---------- ------------------------------------------- ------- ----------------------------------------------
The problem is that you are inserting a new array element instead of creating separate objects.
In the first loop it inserts an empty object into the array, and in the second loop it adds each of the properties, according to
claves
and using the index of the first loop to access the corresponding position: