skip to Main Content

I am new to JS and I am trying to not include the keys which are null when sent with metadata. Foe ex I should not send tags and owner as they are null but send only filepath as it has value. How can I achieve this?

const metadata = {
        filepath: file.name,
        tags: [''],
        owner: '',

    };

    const formData = new FormData();
    formData.append('file', file);
    formData.append('metadata', JSON.stringify(metadata));

    axios.post('http://localhost:8000/fileUpload', formData, {
        onUploadProgress: (event) => {
       
            }));
        },
    })

2

Answers


  1. You can try the following way

    const removeEmptyKeys = (data) => {
      Object.keys(data).forEach((key) => {
        if ((data[key] === '' || data[key] == null || data[key].length === 0)) {
          delete data[key];
        }
      });
    };
    

    Then call the function just before supplying the metadata

    removeEmptyKeys(metadata);
    
    formData.append('metadata', JSON.stringify(metadata));
    

    Cheers.

    Login or Signup to reply.
  2. The tags key is array. You can remove those with the use of filter method.

    const removeEmptyKeys = (data) => {
      Object.keys(data).forEach((key) => {
        if ((data[key] === '' || data[key] == null || data[key].length === 0)) {
          delete data[key];
        }
       if (Array.isArray(data[key]) && data[key].filter(i => i.trim() !=="").length==0){
          delete data[key]  
        }
      });
    };
    

    and feel free to study about js truthy and falsy concept.
    https://developer.mozilla.org/en-US/docs/Glossary/Truthy

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search