What is the process of mapping an object from a JSON file to a different object?

Displayed below is my file

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

The data array may contain additional items.

I am tasked with converting these values into an interface structure as follows:

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

I am required to adhere to this established interface. Therefore, I am attempting to devise a pseudo code approach.

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,
  //...
 }
}
 

Answer №1

It seems like you were attempting to utilize a conversion mapping function named convertToInterfacePerson, but it appears that you hadn't set it up yet before trying to use it. The snippet of code below illustrates its declaration and usage within a map Array method call. This setup should address the error(s) you encountered.

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

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

// Declaration of the conversion mapping function (with optional parameter typing)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
  return {
    id: value.id,
    title: ((value.gender === "m") ? "Mr" : "Mrs"),
    firstName: value.firstName,
    lastName: value.lastName,
    age: String(value.data.age),
    location: value.data.born
  };
}

// Assignment of the list based on the returned array from the mapping function
const list = sourceJson.data.map(convertToInterfacePerson);

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

For a practical demonstration, you can access this TypeScript Playground script that includes this solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform RestApi object information into an Array?

How can I transform the data fetched from PokeApi into an Array that can be used in Angular? When trying to assign it to an Array directly in HTML, it gives an error due to its Object return type. getPokemonDetail(index) { return this.http.get(`${this ...

I am encountering an issue trying to create a Docker image featuring TypeScript

I am facing an issue while trying to build a docker image using the docker build . command in my next.js app An error is being encountered Error: buildx failed with: error: failed to solve: process "/bin/sh -c yarn run build" did not complete su ...

Galaxy S3 JSON Parsing Problem

I have been developing a small application that retrieves the current geographical coordinates and returns the corresponding address using json objects. I have encountered an issue where the app works perfectly on Samsung Galaxy S, but encounters a runtime ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...

Show the HTTP entity response data in a ListView on an Android app display

I am looking to showcase the HttpEntity response values in a listview. Below is the code snippet: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); // w ...

An issue has occurred: The function _co.deleteConsulta is not recognized as a valid function

While following a tutorial on creating a CRUD application using Firestore, I encountered an issue when trying to delete data from Firestore. Every time I attempt to delete a user from my Firestore database, I receive an error stating that ._co.deleteConsul ...

Managing date fields retrieved from a REST Api in AngularJS

One of the challenges I'm facing involves a REST API that sends back JSON data with dates formatted in ISO-8601 style: yyyy-MM-ddTHH:mm:ss: { id: 4 version: 3 code: "ADSFASDF" definition: "asdflkj" type: "CONTAINER" value: "12 ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes: [ { "title": "This is a title", "body": "Body :)", "pub_da ...

TypeScript anonymous class-type Higher Order Component (HOC)

Struggling with creating a generic Higher Order Component (HOC) due to type issues. Let's start with a simple example: class Abc extends React.Component<{}> { hello() { } render() { return <View /> } } Referenc ...

Using SwiftUI to automatically refresh remote JSON data when the app is launched

As a beginner (and my code/model is proof of that, so please be gentle!), I am attempting to create a recipes style (cenotes) app for the first time. To enable data updates without requiring users to reinstall, I have set up a remote JSON file. The app ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this: <script> var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998'; //auto-generated var myValues = ...

Harvesting data from a simulated environment on the web

I'm currently facing a challenge while attempting to extract data from simulator websites. I am encountering difficulty in obtaining the JSON structure necessary for my task. Here is what I have attempted so far: import requests url_puzzle = ' ...

JavaScript: Navigating function passing between multiple React components

I'm currently working on a React Native application utilizing TypeScript. In my project, there is a component named EmotionsRater that can accept two types: either Emotion or Need. It should also be able to receive a function of type rateNeed or rate ...

Issue TS2345: Cannot use type 'Product | undefined' as an argument for type 'Product[] | PromiseLike<Product[]>'

Having trouble retrieving my products using their IDs You can find the code here ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

Check if a form field's value is lower than another in Angular reactive forms

In the form, I have a field called LDC along with two other fields named limit1 and limit2. My goal is to display an error message if either limit1 or limit2 exceeds the value of LDC, or if the sum of limit1 and limit2 surpasses LDC. I attempted to creat ...

Traversing JSON Data (Foursquare API)

My goal is to extract information from a JSON file, with a segment provided below. The objective is to iterate through the data to retrieve all the category names and produce the result, such as "Convenience Store" in this instance. { 'meta': ...

Conversion of JSON data into NSManagedObject

After receiving JSON data from a web service, I am required to store it locally using Core Data as part of a synchronization process that occurs at set intervals. The process involves converting the JSON into NSManagedObject and checking if it already exis ...