JSFiddle - React, Tailwind, and code Playground

by brigand

JavaScript

const x = {
  formType: 'formGroup',
  erroneousField1: 'maybe a tsring',
  email: {
    formType: 'formField',
    htmlName: 'field_email_name',
    value: '[email protected]'
  },
  state: {
    formType: 'formGroup',
    erroneousField2: 3,
    stateCode: {
      formType: 'formField',
      htmlName: 'field_stateCode_name',
      value: 'AZ'
    }
  }
};

// should return an object like this
const y = {
  'field_email_name': '[email protected]',
  'field_stateCode_name': 'AZ'
};

function parse(form) {
  const result = {};

  const inner = (value) => {
    for (const v of Object.values(value)) {
      if (v && typeof v === 'object') {
        if (v.formType === 'formGroup') {
          inner(v);
        } else if (v.formType === 'formField') {
          result[v.htmlName] = v.value;
        }
      }
    }
  };

  inner(form);

  return result;
}

console.log(parse(x));