Hey Friend,
I want to share with you six functions I've come to learn of during the course of data-mockup development, a web app that helps you generate data to be used in your projects, either in JSON, CSV, or SQL. Are you ready to see them? Let's get started!
1. The Copy Function
<pre ref="data">{{data}}</pre>
onCopy() {
const el = document.createElement("textarea");
el.value = this.$refs.data.textContent;
document.body.appendChild(el);
el.select();
document.execCommand("copy");
document.body.removeChild(el);
console.log("coppied");
}
This method when you hook to a button, on clicking it will create an HTML element. It will assign the text content of another HTML element with an id="data" attribute as its value. Next, it will append it to the body and execute the copy command. This function could come in handy when writing a function to copy a piece of code.
2. The JSON to CSV Function
toCSV(obj) {
return `${Object.values(obj).join(", ")}`;
}
This powerful method returns a string containing the values of an object separated with commas. Its so efficient when used within a loop function.
3. The JSON to SQL Function
toSQL(obj) {
return `
INSERT INTO ${this.table.name
(${Object.keys(obj).join(", ")}) VALUES
(${Object.values(obj).join(", ")});
`;
}
This wonderful method returns a string containing the keys and values of an object separated with a semicolon. It's also efficient when used within a loop function.
4. The Iterator Function
iterator(arr, func) {
const result = [];
arr.filter((d) => result.push(func(d)));
return result;
}
This gorgeous method accepts an array of objects and a function and applies the function on each of those objects before returning a new array.
For example, it could be used along with the toSQL and toCSV functions in this manner!
axios
.post("https://app.fakejson.com/q", payload)
.then((res) => {
this.json_data = res.data;
// Passing functions to the Iterator method.
this.csv_data = this.iterator(res.data, this.toCSV);
this.sql_data = this.iterator(res.data, this.toSQL);
})
.catch(error => console.log(error));
5. The Array to Object Function
toObj(arr) {
return arr.reduce((acc, cur) => {
acc[cur.key] = cur.value;
return acc;
}, {});
}
This function can easily convert an entire array to one object, let's see the example below!
const arr = [
{key: 1, value: 'a'},
{key: 2, value: 'b'},
{key: 3, value: 'c'}
]
toObj(arr)
// Output: {1: "a", 2: "b", 3: "c"}
You can also tweak this method to convert an array of objects to a simple one-dimensional array!
function toArr(arr) {
return arr.reduce((acc, cur) => {
acc.push(cur.value);
return acc;
}, []);
}
toArr(arr)
// Output: ["a", "b", "c"]
6. The Download File Function
downloadFile(text, name) {
const a = document.createElement("a");
const type = name.split(".").pop();
a.href = URL.createObjectURL(
new Blob([text], { type: `text/${type === "txt" ? "plain" : type}` })
);
a.download = name;
a.click();
}
This amazing function takes two arguments in its parameter, a text & the file name, and goes ahead converting the text to a file type according to the file extension supplied within the file name.
Summary
To summarize, working on the data-mockup project was fun as it exposed me to some hidden strategies for writing general-purpose functions that could be helpful to other programmers!
I hope this post was helpful to you, thanks!
Top comments (2)
In the array to object, if one of your array items is an object then I believe the nested object will only be a pointer to the original object. If you need a brand new copy then you will need to spread the value using acc.push(...cur.value)
If the new object contains its own nested objects, even in the new object these will be pointers to the originals. Deep (recursive) cloning is difficult and expensive. The lodash library has deep cloning functions
I feel like you could replace your iterator function with the map method.