node.js 如何循环遍历 JSON 对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23117752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:10:04  来源:igfitidea点击:

How can I loop through an array of JSON objects?

jsonnode.jsmongodbexpressmongoose

提问by Chris Paterson

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:

我有需要循环的 JSON 数据。数据位于名为“people.json”的文件中,其结构如下所示:

[{"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?

不过,我无法让它发挥作用。我究竟做错了什么?

回答by Ibrahim

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) {});
  }
});

回答by hedzr

ES6 for..ofcan do that too.

ES6for..of也可以做到这一点。

fs.readFile('./people.json', 'utf8', function (err,data) {
  for(var item of data) {
     console.log('item: ', [item.firstname, ...]);
  }
});