Transform/map json to another format

115 views Asked by At

Have long JSON object and small part is below:

const valueObject = {zipCode: 12345, street1: 'street 1', street2: 'street 2',city:'cityname', uniqueNum: '123456789'};
const mappingObject = {address: {pinCode: zipCode, addressLine1: 'street1', addressLine2:'street2', id: 'uniqueNum', city: city}
const formatObject = {address: {pinCode: '', addressLine1: '', addressLine2:'', id: '0', city: ''}

Trying to transform valueObject to formatObject using mappingObject. (if valueObject has no value then use default value from formatObject) It doesn't get work. Seems have a object and not an array. Not sure what is wrong here, Or does it need to merge.

Object.keys(formatObject).map((k)=>{k: valueObject[mappingObject[k]] || mappingObject[k]});

Output expected:

{address: {pinCode: 12345, addressLine1: 'street 1', addressLine2: 'street 2',city:'cityname', id: '123456789'};

In case, any better option through ES6 ( Else case, using for loop and prepare object. )

1

There are 1 answers

1
daylily On BEST ANSWER

You actually do not need the formatObject here because the mappingObject gives the full transformation schema, i.e. the relation between two structures. formatObject merely serves as an example of what the possible output looks like.

A feasible implementation would be:

function transform(schema, x) {
  return Object.fromEntries(Object.entries(schema).map(([k, v]) => {
    if (typeof v === 'string') return [k, x[v]]
    else if (typeof v === 'object') return [k, transform(v, x)]
    else throw new TypeError(`Schema entry cannot have type ${typeof v}`)
  }))
}

transform(valueObject, mappingObject)

that works recursively through the schema to transform a flat-structured object (in this case valueObject) to a nested-structured object.