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/
JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.
Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
.filter(questions)
. The last )
shouldn't be there.{question: "..."}
, not a string.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);
console.log
instead of alert._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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With