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
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
and spell them all out manually. The library does this for you.
mime.lookup(".md")
will betext/markdown
– an simple transformation that is already beyond the complexity of your current approach.The is no
obj.key
, you just want to compare the variablekey
.When the key isn’t
image
ortext
, you need to loop over all the values, creating the correspondingapplication/XXX
keys in the result.