Lo que quiero es insertar un índice de campo en mi matriz
Mi código que recibo mis arreglos es así:
const onFinish = (values) => { values.fields.map((el, idx) => { console.log({ ...el, index: idx }); //returns each object correctly, but how can I join these objects }); addFields({ formName: 'TABLE NAME', fields: values.fields }).then(() => { //API CALL WHICH RETURNS A RESPONSE }); }; values.fields es la matriz que quiero que funcione
matriz de valores.campo:
[ { "field": "Peso do bezerro (kg)", "fieldtype": "Numeric" }, { "field": "test", "fieldtype": "Text" }, { "field": "Obs", "fieldtype": "Text" } ] Esta matriz puede tener objetos 'x', lo que quiero es que cada uno agregue un campo llamado índice ( which will get if it's the first and add 0 if the second will add a 1 and following... ). Alguien sabe cómo hacer funciona ?
Simplemente puede iterar para cada elemento y agregar el índice como se muestra a continuación:
const onFinish = (values) => { console.log(values.fields); const fields = values.fields.map((item, index) => {...item, index}); addFields({ formName: 'TABLE NAME', fields }).then(() => { //API CALL WHICH RETURNS A RESPONSE }); };Aquí hay una función simple:
const yourArray = [{ "field": "Peso do bezerro (kg)", "fieldtype": "Numeric" }, { "field": "test", "fieldtype": "Text" }, { "field": "Obs", "fieldtype": "Text" } ] yourArray.forEach((item, i) => { item.index = i + 1; }); console.log(yourArray);