简体   繁体   English

对于每个 object 数组,如何向其中添加字段?

[英]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:我收到 arrays 的代码是这样的:

  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.fields是我想让它工作的数组

values.field array: values.field 数组:

[
    {
        "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?这个数组可以有'x'对象,我想要的是为每个添加一个名为 index 的字段( which will get if it's the first and add 0 if the second will add a 1 and following... )。有人知道如何制作这行得通?

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:这是一个简单的 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何向数组中的每个 object 添加一个字段,并使用 react 和 javascript 将该结果数组推送到另一个数组? - How to add a field to each object in array and push that result array to another array using react and javascript? 根据其他字段向数组的每个 object 添加字段 - Add field to each object of an array based on other field 如何为数组中的每个对象添加fadeIn()方法 - How to add fadeIn() method for each object in an array 如何将对象添加到每个对象数组 - How to add an object to each array of objects 如何使用JavaScript将字段添加到数组的每一行? - How can I add a field to each row of an array with Javascript? 向数组中的每个对象添加属性 - Add property to each object in the array TypeScript-如何将“键值”对添加到数组中的每个对象? - TypeScript- How to add a Key Value pair to each object in an Array? 如何为数组中的每个对象添加唯一 ID? - How can I add a unique ID to each object in an array? 如何在 JavaScript 中为 JSON 数组中的每个对象添加一个 ID? - How to add an ID for each object inside JSON array in JavaScript? 如何将每个键对从此对象添加到数组中作为新对象? - How to add each key pair from this Object into an Array as new Objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM