使用underscore.js过滤js对象

时间:2012-08-12 19:03:55

标签: javascript filter

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

  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/

3 个答案:

答案 0 :(得分:15)

  1. 您已使用.filter(questions)关闭了函数调用。最后)不应该在那里。
  2. 通过迭代数组并使用每个元素调用函数来进行过滤。这里,每个元素都是一个对象{question: "..."},而不是一个字符串。
  3. 检查是否相等,而您要检查问题字符串是否包含某个字符串。你甚至希望它不区分大小写。
  4. 您无法提醒对象。请改用控制台和console.log
  5. 所以: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);
    

答案 1 :(得分:3)

这是一个工作版本:

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的函数需要以相同的方式检查每个对象。

答案 2 :(得分:0)

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');

    }

})