簡體   English   中英

使用underscore.js過濾js對象

[英]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/

  1. 您使用.filter(questions)關閉了函數調用。 最后一個)不應該在那里。
  2. 過濾通過迭代數組並使用每個元素調用函數來工作。 這里,每個元素都是一個對象{question: "..."} ,而不是一個字符串。
  3. 檢查是否相等,而您要檢查問題字符串是否包含某個字符串。 你甚至希望它不區分大小寫。
  4. 您無法提醒對象。 請改用console和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);

問題已解決:

  • Parens沒有正確放置。
  • 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM