'filling an array in typescript/react with objects converted from JSON array
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 1:[1]
Let's assume you have some data like this:
[
{ id: 1, name: "test-1" },
{ id: 2, name: "test-random" },
{ id: 3, desc: "444" }
]
And you have some structure of this data, create an interface
interface SomeInterface {
id: number;
name?: string;
desc?: string;
}
Now it's simple if that JSON input data is referred to as someData and resultant data are referred as hmm, you can some something like this:
const hmm: SomeInterface[] = [];
someData.map((data) => {
hmm.push(data as SomeInterface);
});
You can also simplify by:
hmm: SomeInterface[] = someData as SomeInterface[];
Here is a codesandbox, feel free to play with it: https://codesandbox.io/s/dreamy-chatelet-hr5ub6?file=/src/App.tsx:343-456
And here are two sof threads both on same question though, discussing why interface over types:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
