简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM