0

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" 
    }
  }

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.