[英]How to join two arrays in a map function?
我想要加入我從 map function 獲得的 arrays。
我試着做reduce
:
const onFinish = (values) => {
values.fields.map((el, idx) => {
console.log({ ...el, index: idx }); // this `console.log` prints me one array after the other
}).reduce((acc, x) => {console.log(acc,x)}); // I tried with `reduce` but it prints me null
還嘗試使用useState
:
const onFinish = (values) => {
values.fields.map((el, idx) => {
if (myArray === null){
setMyArray(() => {
return { ...el, index: idx };
});
}
else {
setMyArray(() => {
return {...myArray,...el, index: idx };
});
}
});
console.log(myArray) // at my first call to this const onFinish myArray is printed as [] and at the second it prints with the last object only
};
有人知道如何讓這些對象joined/merged
嗎?
雖然從截圖中仍然不是很清楚(總是更喜歡使用文本而不是圖像作為數據/代碼),但看起來你想要
const onFinish = (values) => {
const updatedValues = values.fields.map((field, index) => ({...field, index}));
console.log( updatedValues );
}
這有幫助嗎?
if (myArray === null){
setMyArray(() => {
return [{ ...el, index: idx }];
});
}
else {
setMyArray(() => {
return [...myArray, {...el, index: idx }];
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.