filling an array in typescript/react with objects converted from JSON array

Issue

I have a JSON-File with about 700 lines filled with devices and some information about them (i.e. serial number,macadress, port …).

In another file I have created an object like

type jsonObj = {
serialNumber: string;
macAdress: string;
port: string;
}

And now I want to populate a table with this jsonDevice objects in a loop but somehow I dont get it to work.

My code looks like that:

const ObjectTable: FC = () => {
  const entities: jsonObj[] = [
    {
      serNom: jsonDevices[0].serNom,  //jsonDevices is my json file
      macAdr: jsonDevices[0].macAdr,
      tunPort: jsonDevices[0].tunPort
    },
  ]; 

FC is an import from react and with the code above it is working. Im receiving a table-output with the data for this line (e.g jsonDevices[0].serNom gives me correctly 123456789) but now I want to automatically fill the whole list/array with all the remaining lines from the json devices. In Java I would have solved it with a loop like that:

for (int i = 0, i<jsonObj.length, i++){
    ObjectTable.add(jsonObj[i].serNom);
    ObjectTable.add(jsonObj[i].macAdr);
    ObjectTable.add(jsonObj[i].tunPort);
    }

Please help me. I getting headache from this issue.

Solution

Note: Your code will not compile because you’ve declared the jsonObj type to have this shape:

type jsonObj = {
  serialNumber: string;
  macAdress: string;
  port: string;
}

But then you’re attempting to create an array of jsonObj objects that use different key names:

{
  serNom: jsonDevices[0].serNom,  //jsonDevices is my json file
  macAdr: jsonDevices[0].macAdr,
  tunPort: jsonDevices[0].tunPort
}

With that aside, the solution to your problem is much simpler than it seems: Array.prototype.map:

const entities: jsonObj[] = jsonDevices.map((device) => {
  return {
    serialNumber: device.serNom,
    macAddress: device.macAdr,
    port: device.tunPort,
  };
});

Another note: These abbreviated variable names are difficult to read. I recommend picking one convention and sticking with it. If your JSON file were to follow the naming convention of jsonObj, then you wouldn’t even need to map the JSON to a different shape—you would just do this:

const entities = jsonDevices as jsonObj[];

(This is known as a type assertion—using the as keyword followed by a type to assure the TypeScript compiler that the left-hand value is of the specified type.)

Answered By – AleksandrH

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.