Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converts all JavaScript object bracket selectors with JavaScript object dot notation within file
'use strict';
// may result in mixed object notation if a [var] || [fn] value is used within a object notation > 2 levels
// also will result in mixed object notation if a non-converting ["k-e-y"] is nested (e.g. [][]) with a converting ["key"].
// Run with ES6 compatible runtime (recent Node or Babel) `node objectDotNotation.js file.js outFile.js` or
// `const dotIt = require('objectDotNotation')
// dotIt('file.js','outFile.js');
const fs = require('fs'),
file = process.argv[2],
outFile = process.argv[3];
var changeToDots = (file, outFile) => {
return fs.readFile(file, 'utf8', function(err, doc){
let outString = '' + doc[0],
startKey = -1,
line = 1;
console.log("Reading file...");
console.log("Converting keys...");
console.log(doc);
for(var i=1; i<doc.length; i++){
if( doc[i] === '[' && doc[i-1] !== ']' && startKey < 0){
if(doc[i+1] === '"' || doc[i+1] === "'"){
startKey = i+2;
} else {
outString += doc[i];
}
} else if( startKey >= 0) {
if ( doc[i] === '-' ) {
outString += doc.substr(startKey - 2, i - startKey + 1);
startKey = -1;
} else if ( doc[i] === ']' ){
if ( doc[i+1] = '[' && ( doc[i+2] !== '"' || doc[i+2] !== "'" ){
outString += doc.substr(startKey - 2, i - startKey + 1);
} else {
outString += '.' + doc.substr(startKey, i - startKey - 1);
}
startKey = -1;
} else if ( /\s/.test(doc[i]) ){
console.log("Exception at line " + line + '. Illegal space character in middle of key.');
break;
} else if ( i === doc.length -1 ){
console.log('Exception at line ' + line + '. Document ended before key finished.');
break;
}
} else {
outString += doc[i];
};
if ( /\n/.test(doc[i]) ) line++;
}
console.log("Writing new file...");
fs.writeFile(outFile, outString, function(err){
if (err) console.log(err);
console.log(outFile + ' created with fancy new dot notations for those lovely object keys!');
});
});
}
module.exports = changeToDots;
changeToDots(file, outFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment