首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为数组对象中的值分配键?

如何为数组对象中的值分配键?
EN

Stack Overflow用户
提问于 2022-09-21 14:18:30
回答 1查看 42关注 0票数 0

在某一组记录中,我能够从输入字段中获取值,并将它们添加到数组中。现在我需要将这些值赋值给键。我试过一种逻辑,但行不通。请参考下面的代码。

代码语言:javascript
复制
const handleChange = (data) => {
    const { id, textVal, dateVal } = data;
    setDataNew((prevInfo) => {
      const newList = [...prevInfo];
      const index = newList.findIndex((datum) => datum.id === id);
      if (index !== -1) {
        if (textVal !== undefined) {
          newList[index].textVal = textVal;
        }
        if (dateVal !== undefined) {
          newList[index].dateVal = dateVal;
        }
      } else {
        newList.push({ id, textVal, dateVal });
      }
      return [...newList];
    });
  };

在控制台中,我得到数据如下所示

我想要数据的形式

代码语言:javascript
复制
0:
  dateData: Fri Sep....
  newId: 6705
  franchise: "Mike John"
1:
  dateData: Sun Sep....
  newId: 6703
  franchise: "Mark Ray"

用新钥匙代替旧钥匙。我试过了

代码语言:javascript
复制
if (textVal !== undefined) {
          newList[index].franchise = textVal;
}
if (dateVal !== undefined) {
          newList[index].dateData = dateVal;
}

但是没起作用..。什么是最好的解决方案?任何建议都会受到高度赞赏。

请参阅代码框链接-> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:856-1029

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-21 14:31:18

您没有始终如一地重命名属性。这样做的工作是:

代码语言:javascript
复制
  const handleChange = (data) => {
    const { id: newId, textVal: franchise, dateVal: dateData } = data;
    setDataNew((prevInfo) => {
      const newList = [...prevInfo];
      const index = newList.findIndex((datum) => datum.newId === newId);
      if (index !== -1) {
        if (newId !== undefined) {
          newList[index].newId = newId;
        }
        if (franchise !== undefined) {
          newList[index].franchise = franchise;
        }
        if (dateData !== undefined) {
          newList[index].dateData = dateData;
        }
      } else {
        newList.push({ newId, franchise, dateData });
      }
      return [...newList];
    });
  };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73802346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档