我试图使用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/
答案 0 :(得分:15)
.filter(questions)
关闭了函数调用。最后)
不应该在那里。{question: "..."}
,而不是一个字符串。console.log
。所以: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);
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');
}
})