[英]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.