如何获取具有相同条件的值数组

时间:2018-05-05 19:43:21

标签: javascript json

我有nodeJS代码

的结果

原始JSON数据:

JS代码:

setInterval(function() {
  var notify = db.get('users')
    .filter({notify: "true"})
    .value()
    console.log("1");
    console.log(notify);

}, 10 * 1000);

结果:

[ { uid: '177098244407558145',
    pubgUser: 'Jengas',
    pubgServer: 'pc-eu',
    notify: 'true' },
  { uid: '407970368847085578',
    pubgUser: 'Lovec_Pokemonov',
    pubgServer: 'pc-eu',
    notify: 'true' },
  { uid: '4307970368847085578',
    pubgUser: 'Lossvec_Pokemonov',
    pubgServer: 'pc-eu',
    notify: 'true' },
  { uid: '407970368847015578',
    pubgUser: 'SDLovec_Pokemonov',
    pubgServer: 'pc-eu',
    notify: 'true' } ]

我希望得到所有uid值为“true”的值。但结果是console.log(notify.uid);

给了我“undefined”

预期结果:177098244407558145, 407970368847085578, 4307970368847085578, 407970368847015578

2 个答案:

答案 0 :(得分:3)

您可以将map方法与filter结合使用。

为此,您必须为这两种方法中的每一种传递回调函数,或者只使用特定于arrow的最新版本的ES函数。

let data = [ { uid: '177098244407558145', pubgUser: 'Jengas', pubgServer: 'pc-eu', notify: 'true' }, { uid: '407970368847085578', pubgUser: 'Lovec_Pokemonov', pubgServer: 'pc-eu', notify: 'true' }, { uid: '4307970368847085578', pubgUser: 'Lossvec_Pokemonov', pubgServer: 'pc-eu', notify: 'true' }, { uid: '407970368847015578', pubgUser: 'SDLovec_Pokemonov', pubgServer: 'pc-eu', notify: 'true'}  ]
    
uid_array = data.filter(a => a.notify).map(a => a.uid);
console.log(uid_array);

答案 1 :(得分:1)

通知类型是字符串,因此我们需要检查'true'

let data = [ { uid: '177098244407558145', pubgUser: 'Jengas', pubgServer: 'pc-eu', notify: 'true' }, { uid: '407970368847085578', pubgUser: 'Lovec_Pokemonov', pubgServer: 'pc-eu', notify: 'true' }, { uid: '4307970368847085578', pubgUser: 'Lossvec_Pokemonov', pubgServer: 'pc-eu', notify: 'true' }, { uid: '407970368847015578', pubgUser: 'SDLovec_Pokemonov', pubgServer: 'pc-eu', notify: 'false'}  ]
    
uid_array = data.filter(a => a.notify==='true').map(a => a.uid);
console.log(uid_array);