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/
.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. 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.