Filter through js objects using underscore.js

I am trying to filter out this javascript object using underscore.js, but I don’t know why it doesn’t work, I need to find any value of the question that has a “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? 

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

+7
source share
3 answers
  • You closed the function call with .filter(questions) . Last ) should not be.
  • Filtering works by iterating over an array and calling a function with each element. Here, each element is an {question: "..."} object, not a string.
  • You check for equality, while you want to check if the question line contains a specific line. You even want it to be case insensitive.
  • You cannot identify 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); 
+15
source

Here is the 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); 

fixed:

  • Parens were not placed correctly.
  • Use console.log instead of warning.
  • You should probably use a regular expression to search for "how" when repeating each question.
  • _filter over the array. Your array contains objects, and each object contains a question. The function you pass to _filter should check each object in the same way.
+3
source
 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'); } }) 
0
source

All Articles