簡體   English   中英

使用JavaScript或jQuery過濾數組

[英]Filter array with JavaScript or jQuery

我想過濾下面的數組,並刪除類型等於相同名稱且為false的已定義變量的所有對象。

在下面的示例中,應將包含type:second的元素從數組中刪除。

var first = true,
  second = false,
  third = true,
  obj = {"data": [
    {"type":"first","message":"This is the first message"},
    {"type":"second","message":"This is the second message."},
    {"type":"third","message":"This is the third message."}
]};

data = obj.data;

var filtered = $.grep(data, function(v) {
    return ....
});

console.log(filtered);

http://jsfiddle.net/ejPV4/642/

代替變量,使用類型作為鍵的對象。

var flags = {
    first: true,
    second: false,
    third: true
};
var filtered = $.grep(data, function(v) {
    return flags[v.type];
});

您不需要jQuery。 一個簡單的過濾器將起作用。 我不確定是否可以將字符串作為eval之外的變量名進行比較,甚至不確定是否建議使用此方法。 我建議簡單地將類型設置為boolean並執行以下操作:

const validation = {
  first: true;
  second: false;
  third: true;
};
let filtered = data.filter(v => validation[v.type]);

您不能(技術上可以,但實際上不應該)在JavaScript中具有可變變量。 改用對象。

var types = ['second'];
var filtered = $.grep(obj.data, function(element, index) {
  return types.indexOf(element.type) === -1;
});

您可以通過將它們包括在類型數組中來設置要過濾掉的類型。

現場例子

jsfiddle

var obj = {"data": [
        {"type":"first","message":"This is the first message"},
        {"type":"second","message":"This is the second message."},
        {"type":"third","message":"This is the third message."}
    ]};

    var result = obj.data.filter(function(elem, index){
        return elem.type != "second";
    })

    console.log(result);

更新嘗試使用: http : //jsfiddle.net/ejPV4/646/

    function Stuff(){

        obj = {"data": [
              {"type":"first","message":"This is the first message"},
              {"type":"second","message":"This is the second message."},
              {"type":"third","message":"This is the third message."}
                    ]};
    Stuff.prototype.filter = function(item){
            data = obj.data;
        var remove = "";
        this.item = item;

            $.each(data,function(i,value){
              if(value.type == item){
                remove = i;
              }                 
                    });
          data.splice(remove, 1);
          return data;
     };
}

var think = new Stuff();
console.log(think.filter('first'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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