Home > Software design >  replace array with new array in object javascript
replace array with new array in object javascript

Time:03-18

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:

  1. filter already returns a new array so you don't need to make a copy of userData.emailAlt - just iterate over it.

  2. Watch your spelling (handleDelteMail should probably be handleDeleteMail).

  3. 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)
  • Related