簡體   English   中英

如何在 map function 中加入兩個 arrays?

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

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