JuleVerne
JuleVerne

Reputation: 11

How to map an object from JSON file to another object?

Here is my file

{
  "data": [
    {
      "firstName": "Tom",
      "lastName": "Yoda",
      "type": "guest",
      "id": "0",
      "gender": m,
      "data": { "age": 26, "born": "UK" }
    },
  ]
}

This data array could have more entries.

I have to map the values into an interface which looks like:

InterfacePerson {
 id: string;
 title: string;
 firstName: string;
 lastName: string;
 age: string;
 location: string;
}

I am unable to change the interface. So I'm trying to do some pseudo coding.

const list;

list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
 return {
  id: value.id,
  title: if(value.gender === "m")? "Mr" : "Mrs",
  firstName: value.firstName,
  lastName: value.lastName,
  age: value.data.age,
  //...
 }
}
 

Upvotes: 0

Views: 1973

Answers (1)

phentnil
phentnil

Reputation: 2279

I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.

// Copied in the JSON for demonstration
const sourceJson = {
  "data": [
    {
      "firstName": "Tom",
      "lastName": "Yoda",
      "type": "guest",
      "id": "0",
      "gender": "m",
      "data": { "age": 26, "born": "UK" }
    },
  ]
};

// Declared the InterfacePerson interface
interface InterfacePerson {
  id: string;
  title: string;
  firstName: string;
  lastName: string;
  age: string;
  location: string;
}

// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
  return {
    id: value.id,
    // Removed the `if` statement due to ternary conditional
    title: ((value.gender === "m") ? "Mr" : "Mrs"),
    firstName: value.firstName,
    lastName: value.lastName,
    // Wrapped the value.data.age in a string conversion
    age: String(value.data.age),
    location: value.data.born
  };
}

// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);

// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));

And for a live example, check out this TypeScript Playground script containing this solution.

Upvotes: 1

Related Questions