Home > database >  why my lodash cloneDeepWith method only run once?
why my lodash cloneDeepWith method only run once?

Time:01-10

I have a very very very deep nested object state.

and i want to change all id properties at once with lodash cloneDeepWith methods.

i'm using cloneDeepWith and only works on first match. if i dont return the modified object then it won't modifiy anything. and if i return the value i think the function stops. the function its working ok but the only problem is that only will run once.

  const handleChangeIds = (value) => {
    if (value === sections) {
      const modifiedObject = cloneDeepWith(value, (sectionsValue) => {

        if (sectionsValue && Object.hasOwn(sectionsValue, 'id')) {

          const clonedObj = cloneDeep(sectionsValue);
          clonedObj.id = generateObjectId();
          return clonedObj;

          // I Also Tried sectionsValue = clonedObj; its the same behavior 
        }
      });

      return modifiedObject;
    }
  };

  const DuplicateSection = () => {
    console.log('Original Store', form);
    const store = cloneDeepWith(form, handleChangeIds);
    console.log('Modified', store)
};

CodePudding user response:

For those who want to achieve same thing like me.

I had a super deep nested object for form. and that form had a repeatable functionality.

and i needed to do two thing in generating another form.

  1. generate new Id for every field Id.
  2. clear the input Value.

I solved my problem like this and it works perfectly for a super deep nested object.

import cloneDeepWith from 'lodash/cloneDeepWith';


const clearInputAndChangeId = (sections: FormSectionProps): FormSectionProps => {

  return cloneDeepWith(sections, (value, propertyName, object) => {
    if (propertyName === 'id') return generateObjectId();
    if (propertyName === 'selected') return false;
    if (propertyName === 'checked') return false;
    if (propertyName === 'value') {
      if (object.type === 'file') return [];
      if (object.type === 'checkbox/rating') return 1;
      return '';
    }
  });

};

  • Related