JSFiddle - React, Tailwind, and code Playground

by Hemanth HM

JavaScript

const base = {
  selectedView: 'basicAccount',
  context: {},
  elements: [{
    "name": "email",
    "component": "TextInput",
    "validations": [{
        "type": "required",
        "message": "error.required"
      },
      {
        "type": "email",
        "message": "error.email"
      }
    ],
    "attributes": {
      "type": "email",
      "name": "email",
      "autoComplete": true,
      "label": "basicAccount.email.placeholder"
    }
  }],
  views: [{
    "name": "basicAccount",
    "layout": "layoutType",
    "elements": ["email", "firstName"],
  }, {
    "name": "info",
    "elements": ["header", "name"]
  }],
  "action": {
    data: [],
    error: [],
    path: "uob"
  },
  order: 0
}


const toExtend1 = {
  selectedView: 'basicAccount',
  context: {},
  elements: [{
    "name": "firstName",
    "component": "TextInput",
    "attributes": {
      "type": "text",
      "name": "firstName",
      "autoComplete": true,
      "label": "basicAccount.name.placeholder"
    }
  }],
  views: [{
    "name": "basicAccount",
    "layout": "layoutType",
    "elements": ["middleName", "lastName"],
  }],
  "action": {
    data: [],
    error: [],
    path: "uob"
  },
  order: 1
}

const templateConfig = [base, toExtend1];
const templates = {};

const mergeElements = templateConfig => templateConfig.map(k => k.elements).flat().reduce((acc, val) => {
  if (!acc.length) {
    acc.push(val);
    return acc
  }
  if (acc.name === val.name) return {
    ...acc,
    ...val
  }
  acc.push(val)
  return acc
}, [])

templates.elements = mergeElements(templateConfig)

templates.views = templateConfig.map(k => k.views).flat().reduce((Viewacc, val) => {
  if (!Viewacc.length) {
    Viewacc.push(val)
  }
  let foundElemIndx = Viewacc.findIndex(elem => elem.name === val.name);
  if (!~~foundElemIndx) {
    return Object.keys(Viewacc[foundElemIndx] || {}).map(accVal => {
      if (Array.isArray(val[accVal])) {
        Viewacc[foundElemIndx][accVal] =...