如何根据数组中的元素进行过滤?

时间:2019-08-09 03:35:19

标签: javascript arrays object filter javascript-objects

我有以下多个数组,如下所示:

//Condition one
var categorys = [1, 2];

//useType = 0,Return useType=0 element

//useType = 1,Returns the same categorys element as c_id

var data = [
  {c_id:0, name:'phone', useType:0},
  {c_id:1, name: "milk", useType:1},
  {c_id:2, name: "apple", useType:1},
  {c_id:3, name: "orang", useType:1},
  {c_id:4, name: "red", useType:1}         
]

我做了以下尝试:

let result = data.filter((item, index) => {
  if(item.useType === 0) {
    return true
  } else if(item.useType === 1 && item.c_id === categorys[index]){
    return true
  }
  else {
    return false
  }
});

我想得到以下结果

[
  {c_id:0, name:'phone',useType:0},
  {c_id:1, name: "milk",useType:1},
  {c_id:2, name: "apple",useType:1}
]

但是我只能得到一个

[
  {c_id:0, name:'phone',useType:0},
]

你能帮我吗?

3 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.includes()来检查categories数组是否包含特定的c_id值:

const categories = [1, 2];

const data = [
  {c_id: 0, name: "phone", useType: 0},
  {c_id: 1, name: "milk", useType: 1},
  {c_id: 2, name: "apple", useType: 1},
  {c_id: 3, name: "orang", useType: 1},
  {c_id: 4, name: "red", useType: 1}         
];

const result = data.filter(({useType, c_id}) =>
    useType === 0 || useType === 1 && categories.includes(c_id));

console.log(result);

答案 1 :(得分:2)

您可以使用.filter().includes()方法来获得所需的输出:

const categorys = [1, 2];

const data = [
  {c_id:0, name:'phone',useType:0},
  {c_id:1, name: "milk",useType:1},
  {c_id:2, name: "apple",useType:1},
  {c_id:3, name: "orang",useType:1},
  {c_id:4, name: "red",useType:1}         
];

const result = data.filter(
  ({ c_id, useType }) => ((useType == 0) || (useType == 1 && categorys.includes(c_id)))
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

您需要使用includes

let result = data.filter((item,index)=>{
    if(item.useType === 0){
       return true
    }else if(item.useType === 1 && categorys.includes(item.c_id)){
        return true
    }
    else{
       return false
    }
});

但是要避免在category数组上进行迭代,可以使它成为这样的对象,使其性能更高:

var categories = {
  "1": true,
  "2": true
};

var data = [
  {c_id:0, name:'phone',useType:0},
  {c_id:1, name: "milk",useType:1},
  {c_id:2, name: "apple",useType:1},
  {c_id:3, name: "orang",useType:1},
  {c_id:4, name: "red",useType:1}         
]

let result = data.filter((item,index)=>{
    if(item.useType === 0){
       return true
    }
    
    if(item.useType === 1 && categories[item.c_id] === true){
        return true
    }
    
    return false
});

console.log(result);