Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through an array of JSON objects?

I have JSON data that I need to loop through. The data is in a file titled "people.json" that is structured as listed below:

[{"firstname":"John","lastname":"Smith","age":"40"},{"firstname":"Bill","lastname":"Jones","age":"40"}, ...]

I want to read each object in this file and save it (I'm using Mongoose). Here is what I have so far:

var fs = require('fs');
var Person = require('../models/people');

fs.readFile('./people.json', 'utf8', function (err,data) {
    var i;
    for(i = 0; i < data.length; i++) {
        var newPerson = new Person();
        newPerson.firstname = data[i].firstname;
        newPerson.lastname = data[i].lastname;
        newPerson.age = data[i].age;
        newPerson.save(function (err) {});
    }
});

I'm unable to get this to work though. What am I doing wrong?

like image 808
Chris Paterson Avatar asked Apr 16 '14 18:04

Chris Paterson


People also ask

How do you loop a JSON array?

To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.

How do I iterate over a JSON array of objects?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

How do I iterate through a JSON object?

Use Object. values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

Which loop is used for array of objects?

The outer forEach() loop is used to iterate through the objects array.


Video Answer


1 Answers

fs.readFile('./people.json', 'utf8', function (err,data) {
  data = JSON.parse(data); // you missed that...
  for(var i = 0; i < data.length; i++) {
    var newPerson = new Person();
    newPerson.firstname = data[i].firstname;
    newPerson.lastname = data[i].lastname;
    newPerson.age = data[i].age;
    newPerson.save(function (err) {});
  }
});
like image 167
Ibrahim Avatar answered Sep 23 '22 10:09

Ibrahim