【问题标题】:How to join two arrays in a map function?如何在地图函数中加入两个数组?
【发布时间】:2022-01-13 16:15:33
【问题描述】:

我想要的是加入我从地图函数中获得的数组。

我尝试使用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 吗?

以打印方式采样数据:

我想成为什么样的人:

【问题讨论】:

  • 发布一些示例数据以及您想要的结果
  • 看起来myArray 不是一个数组(?)
  • @James 这是一个对象,但我想加入对象以显示一个数组
  • @GabrielePetrioli 我编辑了,谢谢你的建议

标签: javascript arrays reactjs json


【解决方案1】:

虽然从屏幕截图中仍然不是很清楚(总是更喜欢使用文本而不是图像作为数据/代码),但看起来你想要

const onFinish = (values) => {
  const updatedValues = values.fields.map((field, index) => ({...field, index}));
  console.log( updatedValues );
}

【讨论】:

    【解决方案2】:

    这有帮助吗?

      if (myArray === null){
        setMyArray(() => {
          return [{ ...el, index: idx }];
        });
      }
      else {
        setMyArray(() => {
           return [...myArray, {...el, index: idx }];
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2011-03-06
      • 2019-05-12
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 2015-03-09
      相关资源
      最近更新 更多