JSFiddle - React, Tailwind, and code Playground
by nate
JavaScript
// Create a string with some data. We're pretending we read
// read it from a file somewhere.
let myFile = `a: foo
b: bar
c: baz`;
// read in the file string and turn it into data
function parseFile(file) {
// Turn the file into an array where each line from the
// file string is its own item
let arr = file.split('\n');
// Create a blank object to add key/value pairs to
let data = {};
// Go through the array, adding keys and values
arr.forEach(item => {
item = item.split(':');
data[item[0]] = item[1].trim();
});
return data;
}
// take data and turn it into a filestring
function stringifyData(data) {
// Create a blank string to start with
let str = '';
// Go through the data's keys, writing a new
// line with each key and value
Object.keys(data).forEach(item => {
str += `${item}: ${data[item]}\n`;
});
return str;
}
let stuff = parseFile(myFile);
// Modify the object as much as we like
stuff.nate = 'awesome';
stuff.john = 'still pretty cool';
// Turn it back into a filestring when we're ready
let fileString = stringifyData(stuff);
console.log(fileString);
// write fileString to disc