JSFiddle - React, Tailwind, and code Playground
by sammy
CSS
body { font-family: monospace; white-space:pre;}
JavaScript
var data = [{property:"og:title", content:'OG Testing'},
{property:"og:type", content:'website'},
{property:"og:url", content:'http://jsbin.com/ocedew/4'},
{property:"og:site_name", content:'irrelavent'},
{property:"og:description", content:'This is a test bed for Open Graph protocol.'},
{property:"og:image:src", content:'http://google.com/images/logo.gif'},
{property:"og:image:width", content:'100'},
{property:"og:image:height", content:'100'},
{property:"og:image:src", content:'http://google.com/images/logo2.gif'},
{property:"og:image:width", content:'200'},
{property:"og:image:height", content:'200'}];
var transformed = {};
data.forEach(function (item) {
var key, tmp,
ptr = transformed,
keys = item.property.split(':');
// we want to leave one key to assign to so we always use references
// as long as there's one key left, we're dealing with a sub-node and not a value
while (keys.length > 1) {
key = keys.shift();
if (Array.isArray(ptr[key])) {
// the last index of ptr[key] should become
// the object we are examining.
tmp = ptr[key].length-1;
ptr = ptr[key];
key = tmp;
}
if (typeof ptr[key] === 'string') {
// if it's a string, convert it
ptr[key] = { '': ptr[key] };
} else if (ptr[key] === undefined) {
// create a new key
ptr[key] = {};
}
// move our pointer to the next subnode
ptr = ptr[key];
}
// deal with the last key
key = keys.shift();
if (ptr[key] === undefined) {
ptr[key] = item.content;
} else if (Array.isArray(ptr[key])) {
ptr[key].push(item.content);
} else {
ptr[key] = [ ptr[key], item.content ];
}
});
console.log(transformed);
document.body.textContent = JSON.stringify(transformed, null, 4);