I have an object with two arrays that contain alternative emails and numbers. I'm trying to delete items out of the array and set the new array in the old ones' place.
const handleDelteMail = (evt) => {
let tempData: any = [];
tempData = JSON.parse(JSON.stringify(userData.emailAlt));
let filtered = tempData.filter((mail) => mail._id !== evt.currentTarget.value);
console.log(filtered);
setUserData({ ...userData, [userData.emailAlt]: filtered });
};
filtered holds the correct new array that I want to put into userData, but having no luck.
this is what my userData object looks like:
const initialValues = {
dateCreated: Date.now(),
firstName: "",
lastName: "",
countryCode: "",
numberPrime: "",
numberAlt: [],
companyName: "",
consultant: "",
industry: "",
whatsapp: false,
acceptTerms: false,
emailPrime: "",
emailAlt: [],
skype: "",
userType: "",
agent: "",
comment: "",
};
I don't know what I'm missing or doing wrong. Please help.
CodePudding user response:
filter
already returns a new array so you don't need to make a copy ofuserData.emailAlt
- just iterate over it.Watch your spelling (
handleDelteMail
should probably behandleDeleteMail
).You can reconstruct the new object by assigning the new array to
emailAlt
.
function handleDeleteMail(evt) {
const { value } = evt.target;
const filtered = userData.emailAt.filter(mail => {
return mail._id !== value);
});
setUserData({ ...userData, emailAlt: filtered });
}
CodePudding user response:
You can use function get in module lodash
Try this one:
const _ = require('lodash'); // install `lodash` first
const { value } = evt.currentTarget;
const filtered = userData.emailAt.filter(mail => {
return mail._id !== value);
});
_.set(userData, 'emailAtl', filtered)