簡體   English   中英

對於每個 object 數組,如何向其中添加字段?

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

我想要的是在我的數組中插入一個字段索引

我收到 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是我想讓它工作的數組

values.field 數組:

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

這個數組可以有'x'對象,我想要的是為每個添加一個名為 index 的字段( which will get if it's the first and add 0 if the second will add a 1 and following... )。有人知道如何制作這行得通?

您可以簡單地迭代每個項目並添加索引,如下所示:

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

這是一個簡單的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM