Object to Component structure

by jonahe

Babel + JSX

const convertSimple = {
 "article":[
   {
    "section@role":"Introduction",
    "section":[
      {
        "title@id":"dv_introduction",
        "title@wordstyle":"Section_Header",
        "title":          {
          "annotate@id":"720731008",
          "annotate":"Introduction"
        }
      }
    ]
   }
  ]
};

const jsonUI = {
  type: 'article',
  children: [
    {
      type: 'section',
      props: {
        "section@role": "Introduction"
      },
      children: {
        type: 'title',
        props: {
          "annotate@id":"720731008",
          "annotate":"Introduction"
        }
      }
    }
  ],
};


function toComponentObject(obj) {
	const componentType = getComponentType(obj);
  if(!componentType) return ""; // break, we've reached bottom layer with "annotate"
  
  let props = getComponentProps(obj);
  let componentChildren = obj[componentType];
  const childrenIsArray = Array.isArray(componentChildren);
  const children = childrenIsArray ?
  			// this is the recursive part. if children is an array each of the children gets transformed
        componentChildren.map(toComponentObject) :
        // otherwise we assume children is a single Object, and we try to transform it
  			toComponentObject(componentChildren)
        
  props = childrenIsArray ? 
  	props : 
    // NOTE this may be wrong. May need an extra condition depending on whether 
    // children is an Object or a String (the end case) 
    {...props, ...getComponentProps(componentChildren)};
  return { 
    type: componentType,
    props: props,
    children: children
  };
	
}

function getComponentType(obj) {
	return Object
  	.keys(obj)
    .find(isComponentNameKey); // return key name, or undefined
}

function isComponentNameKey(key) {
	return !key.includes('@') && key != 'annotate';
}

function getComponentProps(obj) {
	const props = {};
	return Object
  	.keys(obj)
    .filter(key => !isComponentNameKey(key))
    .reduce((soFar, nextPropKey) => {
    	const cleanKey =...