0

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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.