How to assign key to a value in an object of array?

Viewed 42

In a certain set of records, I'm able to get the values from input fields and also add them to an array. Now I need to assign those values to keys. I have tried with one logic but doesn't work. Please refer to the code below.

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];
    });
  };

In console I'm getting data as below

enter image description here

I want data in the form of

0:
  dateData: Fri Sep....
  newId: 6705
  franchise: "Mike John"
1:
  dateData: Sun Sep....
  newId: 6703
  franchise: "Mark Ray"

replacing the old keys with the new ones. I have tried with this

if (textVal !== undefined) {
          newList[index].franchise = textVal;
}
if (dateVal !== undefined) {
          newList[index].dateData = dateVal;
}

but, didn't work... What could be the best solution? Any suggestion is highly appreciated

Please refer codesandbox link --> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:856-1029

1 Answers

You didn't rename the attributes consistently. This does the job:

  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];
    });
  };
Related