【问题标题】:filter through js objects using underscore.js使用 underscore.js 过滤 js 对象
【发布时间】:2012-08-12 19:03:55
【问题描述】:

我正在尝试使用 underscore.js 过滤这个 javascript 对象,但我不知道为什么它不起作用,它的意思是找到任何包含“how”的问题值。

  var questions = [
    {question: "what is your name"},
    {question: "How old are you"},
    {question: "whats is your mothers name"},
    {question: "where do work/or study"},
    ];

var match = _.filter(questions),function(words){ return words === "how"});

alert(match); // its mean to print out -> how old are you?

完整代码在这里(underscore.js 已经包含):http://jsfiddle.net/7cFbk/

【问题讨论】:

    标签: javascript filter


    【解决方案1】:
    1. 您使用.filter(questions) 关闭了函数调用。最后一个 ) 不应该在那里。
    2. 过滤通过遍历数组并使用每个元素调用函数来工作。这里,每个元素都是一个对象{question: "..."},而不是一个字符串。
    3. 您检查是否相等,而您想检查问题字符串是否包含某个字符串。您甚至希望它不区分大小写。
    4. 您无法警告对象。请改用控制台和console.log

    所以:http://jsfiddle.net/7cFbk/45/

    var questions = [
        {question: "what is your name"},
        {question: "How old are you"},
        {question: "whats is your mothers name"},
        {question: "where do work/or study"},
    ];
    
    var evens = _.filter(questions, function(obj) {
        // `~` with `indexOf` means "contains"
        // `toLowerCase` to discard case of question string
        return ~obj.question.toLowerCase().indexOf("how");
    });
    
    console.log(evens);
    

    【讨论】:

    • thanks 效果很好,如何将这些值传递到 html 元素中,将它们添加到 div 即foreach question found $('divname').html('<p>' + even.obj + '<p>'); 谢谢:)
    • 我认为您需要详细说明一下。但我认为你需要_.each
    • 对于 Javascript 新手,并没有完全理解示例中的注释,返回行开​​头的 '~' 很重要,整行相当于“obj.question” .toLowerCase().indexOf("how") >= 0" 在这种特定情况下。
    【解决方案2】:

    这是一个工作版本:

    var questions = [
        {question: "what is your name"},
        {question: "How old are you"},
        {question: "whats is your mothers name"},
        {question: "where do work/or study"},
    ];
    
    var hasHow = _.filter(questions, function(q){return q.question.match(/how/i)});
    
    console.log(hasHow);
    

    已修复的问题:

    • Parens 未正确放置。
    • 使用console.log 代替警报。
    • 在遍历每个问题时,您可能应该使用正则表达式来查找“方法”。
    • _filter 遍历数组。您的数组包含对象,每个对象都包含一个问题。您传递给_filter 的函数需要以相同的方式检查每个对象。

    【讨论】:

      【解决方案3】:
      data = {
          'data1' :{
              'name':'chicken noodle'
           },
          'data2' :{
              'name':'you must google everything'
           },
          'data3' :{
              'name':'Love eating good food'
           }
      }
      
      _.filter(data,function(i){
      
          if(i.name.toLowerCase().indexOf('chick') == 0){
      
              console.log(i);
      
          }else{
      
              console.log('error');
      
          }
      
      })
      

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 2021-11-09
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 2014-02-19
        • 1970-01-01
        • 1970-01-01
        • 2017-02-06
        相关资源
        最近更新 更多