[英]filter through js objects using underscore.js
我試圖使用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/
.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);
這是一個工作版本:
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
而不是alert。 _filter
遍歷數組。 您的數組包含對象,每個對象都包含一個問題。 傳遞給_filter
的函數需要以相同的方式檢查每個對象。 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');
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.