0

I have a type that I have defined in its own .ts file

export class FakeType  {
    value:{
        name: string,
        id: number
    },
    x: number
 }

and I have an instance of that object in a .tsx file

let myObj: FakeType;
myObj = {
    value:{
        name: "Foo",
        id: 99
    },
    x: 5
}

How can I programmatically create html elements corresponding to each field?

I can manually create my desired output as follows, but this won't work if FakeType has hundreds of fields

return (
    <div>Value: {myObj.value}</div>
    <div>x: {myObj.x}</div>);

Note that I need access to both the field name and its value when I display it on a webpage.

Mani
  • 27
  • 5

1 Answers1

1

Using Object.keys() you can iterate each key of your object with Array.map() to return the desired HTML and display the value of each object key with myObj[key] syntax.

Working example: https://codesandbox.io/s/react-stackoverflow-60783297-ozjeu

See comments in the code below for explanation...

// Your object.
const myObj: FakeType = {
  value: {
    name: "Foo",
    id: 99
  },
  x: 5
};

// Function to get value of an object with key name and unquote value object props.
// Typing `obj: any` is necessary to avoid TypeScript to complain
// about the type of the key value you're trying to retrieve.
const getValue = (obj: any, key: string) => {
  const value = obj[key];
  const stringify = JSON.stringify(value);
  const unquoted = stringify.replace(/"([^"]+)":/g, "$1:");
  return unquoted;
};

// Loop through `myObj` keys and display its value
// using the `getValue()` function implemented above.
return (
  <React.Fragment>
    {Object.keys(myObj).map(key => (
      <div>
        {key}: {getValue(myObj, key)}
      </div>
    ))}
  </React.Fragment>
);
j3ff
  • 5,719
  • 8
  • 38
  • 51