Home > Software engineering >  ReactJS - Overwrite array if same keys
ReactJS - Overwrite array if same keys

Time:12-09

I want to overwrite the array if the keys are the same. And push if keys are different.
From this:

const fieldData = [
 {
    "field_1": { 
        "value": "oldValue" 
    },
    "field_2": { 
         "value": "oldValue" 
    }
  }
];

const [data, setData] = useState(fieldData);

const pushData = (newData) => {
  setData(current => [...current, newData]);
}

The result if the keys are the same:

 {
    "field_1": { 
        "value": "newValue" 
    },
    "field_2": { 
         "value": "oldValue" 
    }
  }

The result if the keys are diffrent:

 {
    "field_1": { 
        "value": "newValue" 
    },
    "field_2": { 
         "value": "oldValue" 
    },
    "field_3": { 
         "value": "newValue Field 3" 
    }
  }

CodePudding user response:

Here's one way you could approach this:

const fieldData = [  {    "field_1": {         "value": "oldValue"     },    "field_2": {          "value": "oldValue"     }  }];

const [data, setData] = useState(fieldData);

const pushData = (newData) => {
  setData(current => {
    let newFieldData = [...current];
    newFieldData[0] = {...newFieldData[0]}; // create a copy of the first object in the array
    for (const key of Object.keys(newData)) {
      // for each key in the new data object
      if (newFieldData[0][key]) {
        // if the key exists in the first object in the array, update its value
        newFieldData[0][key].value = newData[key].value;
      } else {
        // if the key doesn't exist, add it to the first object in the array
        newFieldData[0][key] = newData[key];
      }
    }
    return newFieldData;
  });
}

This code creates a copy of the first object in the fieldData array, then loops through the keys of the new data object. If the key exists in the copied object, it updates its value. If the key doesn't exist, it adds it to the copied object. The copied object is then returned as the new data.

You can then call the pushData function with a new data object to update the fieldData array:

pushData({
  "field_1": { 
    "value": "newValue" 
  },
  "field_3": { 
    "value": "newValue Field 3" 
  }
});

CodePudding user response:

I would recommend you to work with a different data structure. Change your array and work with a dictionary.

const fieldData =  {
    "field_1": { 
        "value": "oldValue" 
    },
    "field_2": { 
         "value": "oldValue" 
    }
  }

const [data, setData] = useState(fieldData);

const pushData = (newData) => {
  setData(current => ({...current,...newData}));
}

In this case, if you have a new [key, value] it will be added to your object. Otherwise the value will be overridden

  • Related