简体   繁体   中英

filter through js objects using underscore.js

I am trying to filter through this javascript object using underscore.js, but I don't know why it's not working, its meant to find any question value that has "how" in it.

  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?

the full code is here(underscore.js already included): http://jsfiddle.net/7cFbk/

  1. You closed the function call with .filter(questions) . The last ) shouldn't be there.
  2. Filtering works by iterating over the array and calling the function with each element. Here, each element is an object {question: "..."} , not a string.
  3. You check for equality, whereas you want to check whether the question string contains a certain string. You even want it case-insensitive.
  4. You cannot alert objects. Use the console and console.log instead.

So: 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);

Here is a working version:

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

issues fixed:

  • Parens were not correctly placed.
  • Use console.log instead of alert.
  • You should probably use a regexp to find 'how' when iterating over each question.
  • _filter iterates over an array. Your array contains objects, and each object contains a question. The function you pass to _filter needs to examine each object in the same way.
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');

    }

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM