Skip to content

Instantly share code, notes, and snippets.

@stefanbirkner
Created December 19, 2017 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanbirkner/5252641db9f682baabd8c03e526ac5ff to your computer and use it in GitHub Desktop.
Save stefanbirkner/5252641db9f682baabd8c03e526ac5ff to your computer and use it in GitHub Desktop.
JavaScript - Object2YAML
function concat(firstText, secondText) {
return firstText + secondText;
}
function escape(key) {
if (key.match(/^[A-Za-z0-9\-\_]+$/))
return key
else
return `"${key}"`
}
function yaml(object, indent) {
indent = indent || ''
return Object.keys(object)
.map(
key => {
if (typeof object[key] === 'string' || object[key] instanceof String)
return `${indent}${escape(key)}: ${object[key]}\n`;
else
return `${indent}${escape(key)}:\n` + yaml(object[key], indent + ' ');
}
)
.reduce(concat)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment