0

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. )

TechS
  • 167
  • 1
  • 5
  • 14
  • Not sure what you are asking about. It seems your code will return an array. But you said you had an object instead of an array. – daylily Jul 13 '21 at 17:44
  • Yes, above code returning array. but Need single object as `formatObject` , just values need to pick from `valueObject`. – TechS Jul 13 '21 at 17:45

1 Answers1

1

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.

daylily
  • 876
  • 5
  • 11