Home > other >  Separate big array from main component to a new file
Separate big array from main component to a new file

Time:02-02

I'm new in the front end world, and I currently working on Angular project with typescript, and I created an array in order to assign to an object, so I have something like this in my TS component:

    formOptions = []

    ngOnInit() {
        this.formOptions = [{
            id: 1,
            description: 'First name'
          },
          {
            id: 2,
            description: 'Middle name'
          }, {
            id: 3,
            description: 'Last name'
          }...etc
        }

As you can see the array it's going to be supper big, is there a way to move the array to separate file, then import it and just assign the object? If so, where is the common path to save this path of files and what extension I should use for it?

CodePudding user response:

Try storing the array in a separate .json file. Then use fetch to load the file and parse the JSON. JSON is Javascript Object Notation and it will take an array (or object) exactly as you have it laid out in your code.

[{
            id: 1,
            description: 'First name'
          },
          {
            id: 2,
            description: 'Middle name'
          }, {
            id: 3,
            description: 'Last name'
          }...etc
        }]

The first example at MDN does exactly what I describe.

  • Related