使用javascript根据对象的属性从数组中删除对象

给定对象数组:

var items = [
{"rank":"3","color":"red"},
{"rank":"4","color":"blue"},
{"rank":"0","color":"green"},
{"rank":"6","color":"blue"},
{"rank":"0","color":"yellow"}
];

我想删除所有排名为0的条目,因此结果将是:

项目:

[{"rank":"3","color":"red"},
{"rank":"4","color":"blue"},
{"rank":"6","color":"blue"}];
评论
  • Buck
    Buck 回复

    Try to filter by trusy value and apply + sign to convert from string to number:

    var items = [
       {"rank":"3","color":"red"},
       {"rank":"4","color":"blue"},
       {"rank":"0","color":"green"},
       {"rank":"6","color":"blue"},
       {"rank":"0","color":"yellow"}
    ];
    
    result = items.filter(({rank})=> +rank);
    console.log(result);
  • 纯情小火鸡
    纯情小火鸡 回复

    应用过滤器:

    var items = [{"rank":"3","color":"red"},{"rank":"4","color":"blue"},{"rank":"0","color":"green"},{"rank":"6","color":"blue"},{"rank":"0","color":"yellow"}];
    
    result = items.filter(({rank})=>rank>0);
    console.log(result);
  • 静静的思念
    静静的思念 回复
    var items = [
    {"rank":"3","color":"red"},
    {"rank":"4","color":"blue"},
    {"rank":"0","color":"green"},
    {"rank":"6","color":"blue"},
    {"rank":"0","color":"yellow"}
    ];
    
    let filteredArray = items.filter(el => el.rank > 0);
    
    console.log(filteredArray);
  • non_et
    non_et 回复

    您可以使用Array.filter方法执行此操作。

    items = items.filter(i=> {
       return i.rank !== '0';
    });
    
  • 布水风
    布水风 回复

    您可以像这样应用过滤器:

    items = items.filter(el => el.rank != "0")
    
  • 俄还好
    俄还好 回复

    您可以将过滤器添加到Items数组:

    items.filter(item => item.rank > 0)