Search code examples
javascriptlodash

remove nested property value from object


I have a nested object as follows.
I am looking to remove the img property from it.

const myOriginalObject {
    props : {
        isMobile: true,
        data: {
            id: '',
            header: '',
            flag: '',
            desc1: '',
            desc2: '',
            logo: {
                src: '',
                alt: '',
            },
            img: {
                src: '',
                alt: '',
            },
        }
    }
}

It works if I do the following.

myOriginalObject.props.data.img = undefined;

But I looking for a cleaner way to do this rather than setting the value to undefined.
Looking to use unset from lodash.

But it doesn't unset and img value is still there. Can I know what I am doing wrong pls?

  import unset from 'lodash/unset';
  // none of following works. 
    
  unset(myOriginalObject, "img");
  unset(myOriginalObject, myOriginalObject.props.data.image);
  unset(myOriginalObject, myOriginalObject.props.data.image.src);
  unset(myOriginalObject, myOriginalObject.props.data.image.alt);

Solution

  • You're looking for the delete operator.

    delete myOriginalObject.props.data.img;