skip to Main Content

I am having the following object that is being sent as an object to a function,

const mimeTypes = {
  image: [".svg", ".png", ".gif", ".jpeg", ".jpg"],
  application: [".pdf", ".zip"],
  text: [".txt", ".csv"]
};

I need to transform the above object into another object, based on mime type,
The result should look like


const result = {
  "image/*": [".svg", ".png", ".gif", ".jpeg", ".jpg"],
  "application/zip": [".zip"],
  "application/pdf": [".pdf"],
  "text/*": [".txt", ".csv"]
};

Here application level types are handled with their mime types, rest of the types are generic ones and follow image/* or text/*

How do I transform this? I am a beginner to this

function transform(obj){
   let res = {};
   for (const key in obj) {
    if (obj.key === 'image') {
      res["image/*"] = obj.image;
    }
    if (obj.key === 'text') {
      res["text/*"] = obj.text;
    }
   }
   return res;
}

When just const input = { text: [".txt", ".csv"]} is passed, the resultant object should only have text related object. In this case the result should have text related object like
const result = { "image/*":text: [".txt", ".csv"] };

Is there a more simpler and compact version of this?

2

Answers


  1. You’re being unnecessarily clever here. Consider using the 48M+/week downloaded library called mime-types.

    The idea is just to have a simple map

    { 
      ".svg": "image/svg",
      ".png": "image/png",
      /* etc. */
    }
    

    and spell them all out manually. The library does this for you.

    mime.lookup(".md") will be text/markdown – an simple transformation that is already beyond the complexity of your current approach.

    Login or Signup to reply.
  2. The is no obj.key, you just want to compare the variable key.

    When the key isn’t image or text, you need to loop over all the values, creating the corresponding application/XXX keys in the result.

    const mimeTypes = {
      image: [".svg", ".png", ".gif", ".jpeg", ".jpg"],
      application: [".pdf", ".zip"],
      text: [".txt", ".csv"]
    };
    
    function transform(obj) {
      let res = {};
      Object.entries(obj).forEach(([key, extensions]) => {
        if (key === 'image') {
          res["image/*"] = extensions;
        } else if (key === 'text') {
          res["text/*"] = extensions;
        } else {
          extensions.forEach(val => res[`application/${val.substring(1)}`] = [val]);
        }
      });
      return res;
    }
    
    
    console.log(transform(mimeTypes));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search