【问题标题】:How to use filter function to return perticular data in javascript如何使用过滤器函数在javascript中返回特定数据
【发布时间】:2019-01-29 18:57:30
【问题描述】:

如果来自两个不同数据源的 user_id 匹配,我必须返回电子邮件,然后它必须返回来自第一个源的唯一电子邮件。 第一个来源来自 PostgreSQL 的表结果,第二个来源来自 JSON 数据。

我试过这段代码:

var table = db.query(select * from users); //it has 4 fields _id, name, email, phoneNumber
jsondata.map(function(item){
var value = table.rows.filter(function(x) {
    if(x._id === item.user_id) {
        return x.email
    }
});

});

JSON 数据:例如,我在这里只添加了 2 个数据,但我有超过 1000 个数据。那是项目

{
    "_id": "5b56d462c53eb904fcb5a8fc",
    "user_id": 2,
    "date": "2017-08-29T08:22:00.000Z",
    "message": "jfgdshfgdfhgdshg"    
},
{
    "_id": "5b56d462c53eb904fcb5a8fc",
    "user_id": 44,
    "date": "2017-08-28T08:22:00.000Z",
    "message": "jfgdshfgdfhgdshg" 
}

Postgresql 即 x

_id | name | email       | phoneNumber|
---------------------------------------
 2  |  aa  |aa@gmail.com | 98998998   |
 3  |  bb  |bb@gmail.com | 09887665   |
 44 |  cc  |cc@gmail.com | 98765655   |

【问题讨论】:

  • 第二个源是否为数组?
  • 第二个来源的 JSON 数据看起来如何?

标签: javascript node.js filter


【解决方案1】:

你可以这样做

var value = table.rows.filter(x) {
     var mail=[];
    if( JSON.stringify(item.user_id)=== JSON.stringify(x._id)) {
        mail.push(x.email);
    }
 return mail;
});

【讨论】:

  • x._id.equals 不是函数
  • 你可以在post中添加x和item这两个json数据吗?
【解决方案2】:

我认为这两个来源都是数组的形式。请检查以下方法。

  var secondSource = [
    {
      "_id": "5b56d462c53eb904fcb5a8fc",
      "user_id": "1",
      "date": "2017-08-29T08:22:00.000Z",
      "message": "jfgdshfgdfhgdshg"
    },
    {
      "_id": "5b56d462c53eb904fcb5a8fc",
      "user_id": "2",
      "date": "2017-08-28T08:22:00.000Z",
      "message": "jfgdshfgdfhgdshg"
    }
  ];

  var firstSource = [{
      "_id": "1",
      "name": "xx",
      "email": "xxx@gmail.com",
      "phone": "xx"
    },
    {
      "_id": "3",
      "name": "xx",
      "email": "yyy@gmail.com",
      "phone": "xx"
    }
  ];

  // collect user ids from second source
  var userIds = secondSource.map(user => user.user_id);

  // Get filtered emails
  var filteredEmails = firstSource.filter(source => {
    if (userIds.indexOf(source._id) > -1) {
      return source.email
    }
  }).map(function(obj) {
    return obj.email;
  });

  console.log(filteredEmails); // ["xxx@gmail.com"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2022-12-12
    • 2015-02-23
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多