new_coder
new_coder

Reputation: 209

creating multiple javascript objects using a loop that reads from json data

I am trying to create a number of Javscript objects at once by using a loop through json data. I'm having trouble finding a way to do this and if someone could take a look at the below code and suggest the best way of looping through the json data and creating the objects that would be great.

    // Create Test Constructor

    function Test(name, age, address) {
      this.name = name;
      this.age = age;
      this.address = address;
    }

    // Create Test Object
    let test1 = new Test("name[0]", age[0], "address[0]");


    //json data from a seperate .json file

    {
      "Tests": [
         {
           "name": "First Person",
           "age": 20,
           "address": "New York"
         },
         {
           "name": "Second Person",
           "age": 21,
           "address": "The World"
         },
         {
           "name": "Third Person",
           "age": 22,
           "address": "The Universe"
         }
       ]
    }

Thanks

Upvotes: 0

Views: 118

Answers (1)

domenikk
domenikk

Reputation: 1743

If you just need plain objects:

const { Tests } = JSON.parse('//json data from a seperate .json file');

Now Tests should be an array of Test objects.

Upvotes: 1

Related Questions