nodejs按键过滤对象数组

时间:2016-07-20 11:59:59

标签: node.js routes underscore.js

我是nodeJS的新手,因为我正在处理路由并将firstRoute响应的值存储在数组中并过滤第二个Route中的数组值。如下

var _ = require('underscore');
var apiInfo = require('../../utils/email_api');
//apiInfo is utility 

app.get('/api/fleets', function(req, res, next) {
    var fileToRead = pathReader.filePath() + 'fleets.json';
    fs.readFile(fileToRead, 'utf8', function(err, data) {
        if (err) throw err;
         // here I am setting the apiInfo.fleets which has data
        apiInfo.fleets = data;
        res.send(data);
    });
});

和第二个网址

app.get('/api/fleet/:fleet_uuid/vehicles', function(req, res, next) {
    var fleets = apiInfo.fleets;
    //now fleets contains the assigned value in first api call
    //If i pass fleets = [](static array) i can able to filter.
    var fleet_uuid = req.params.fleet_uuid
    ,   fleetFound = _.find(fleets, function(fleet){ return fleet.id === req.params.fleet_uuid; });
    //The fleet Found is always printing undefined(how can i filter the fleet Found)
    console.log(fleetFound);
});

如果我传递fleets = staticArray我能够过滤该值,但是在第一次api调用中分配的动态数组,我能够打印(打印正确的数组值,但不能过滤)

1 个答案:

答案 0 :(得分:0)

您的问题是您正在将文件作为字符串读取而不是将其存储为正确的对象

您需要做的是JSON.parse来自fs.readFile的数据。

所以当你使用_.find时,你正在使用字符串中的每个字符。

例如读取文件:

{
  "data": [1,2,3,4,5]
}

将存储为:

 { fleets: '{\r\n  "data": [1,2,3,4,5]\r\n}\r\n' }

 app.get('/api/fleets', function(req, res, next) {
   var fileToRead = pathReader.filePath() + 'fleets.json';
   fs.readFile(fileToRead, 'utf8', function(err, data) {
     if (err) throw err;
     
     apiInfo.fleets = JSON.parse(data); // parse the data
     res.send(data);
   });
 });