Home > Blockchain >  for each object array, how to add a field into it?
for each object array, how to add a field into it?

Time:01-14

What I want is to insert a field index into my array

My code thar I receive my arrays is like that:

  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 is the array that I want to make it work

values.field array :

[
    {
        "field": "Peso do bezerro (kg)",
        "fieldtype": "Numeric"
    },
    {
        "field": "test",
        "fieldtype": "Text"
    },
    {
        "field": "Obs",
        "fieldtype": "Text"
    }
]

This array can have 'x' objects,What I want is for each add a field named index(which will get if it's the first and add 0 if the second will add a 1 and following...).Someone knows how to make it work ?

CodePudding user response:

You can simply iterate for each item and add the index as shown below:

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
     });
};

CodePudding user response:

Here is a simple function:

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);

  •  Tags:  
  • Related