将用户输入与集合(对象数组)进行比较 - 命令行节点JS

时间:2017-10-12 09:20:06

标签: javascript arrays node.js prompt

我有一些数据存储在一个集合(对象数组)中,我在nodejs 上使用提示符来获取用户的信息,该信息将此数据条目与对象数组进行比较,并且记录字符串,如果为真记录错误,如果不是真的

我需要帮助其他{}部分,我该怎么做呢?请记住,输入将询问cardNo和PIN,然后将这两个值与用户进行比较以返回true或false。

这是我到目前为止所拥有的:

var prompt = require('prompt');
prompt.start(); // Lets you prompt the user for info

// Dummy Users
var users = [{
    name: 'Zayn',
    cardNo: 4317307597302131,
    PIN: 1212
}, {
    name: 'Me',
    cardNo: 4929715360098035,
    PIN: 1213
}, {
    name: 'You',
    cardNo: 4539890581557184,
    PIN: 1313
}, {
    name: 'See',
    cardNo: 4205877325217426,
    PIN: 1314
}, {
    name: 'Who',
    cardNo: 4405488141962985,
    PIN: 1414
}, {
    name: 'Lol',
    cardNo: 4556666088651201,
    PIN: 1415
}];

// Prompt (which is Async) works like this:
prompt.get(['cardNo', 'PIN'], function (err, result) {

    if (err) { // Handle error
        return err;
    }
    else{
        for(var i=0; i < users.length; i++){
           if(users[i].cardNo === result.cardNo && users[i].PIN === result.PIN){
               console.log("valid user");
               //your logic on validation

               break;// use break or return something to stop looping after validation
           }
        }
    }
});

3 个答案:

答案 0 :(得分:0)

您可以迭代您的用户数组,并在提示符中查找具有与结果对象的属性匹配的bookID和PIN属性的对象。

if (err) { 
   console.log(err);
   // Handle error
}
else{
    for(var i=0; i < users.length; i++){
       if(users[i].bookID === result.bookID && users[i].PIN === result.PIN){
           console.log("valid user");
           //your logic on validation

           break;// use break or return something to stop looping after validation
       }
    }
}

答案 1 :(得分:0)

 console.log(
  users.find( user => 
   user.name === result.name &&
   user.PIN === result.PIN
  )
   ?true
   :new Error("not found")
);

答案 2 :(得分:0)

You can use .some() method to test over the users in the array. If it returns a truthy value then the user is valid otherwise it's not.

This is how should be your code:

prompt.get(['cardNo', 'PIN'], function(err, result) {
  if (err) { // Handle error
    return err;
  } else {
    if (users.some(function(u) {
        return u.PIN === result.PIN && u.cardNo === result.cardNo;
      })){
      console.log("valid user");
    } else {
      console.log("invalid user");
    }
  }
});

Demo:

This is a working Demo:

var users = [{
  name: 'Zayn',
  cardNo: 4317307597302131,
  PIN: 1212
}, {
  name: 'Me',
  cardNo: 4929715360098035,
  PIN: 1213
}, {
  name: 'You',
  cardNo: 4539890581557184,
  PIN: 1313
}, {
  name: 'See',
  cardNo: 4205877325217426,
  PIN: 1314
}, {
  name: 'Who',
  cardNo: 4405488141962985,
  PIN: 1414
}, {
  name: 'Lol',
  cardNo: 4556666088651201,
  PIN: 1415
}];

result = {
  cardNo: 4405488141962985,
  PIN: 1414
};

if (users.some(function(u) {
    return u.PIN === result.PIN && u.cardNo === result.cardNo;
  })) {
  console.log("valid user");
} else {
  console.log("invalid user");
}