猿问

根据另一个对象数组中的过滤条件来过滤对象数组:JavaScript

我希望myArray根据中提到的条件进行过滤myFilter。myFilter的键已定义,可以使用进行访问myFilter.field,myFilter.value其中as的key:valuemyArray未知。我们可能必须遍历每个对象,myArray才能首先将myArray [key]与匹配myFilter.field,然后再将myArray [key]与myFilter.value进行匹配。


那应该是AND逻辑


myArray = [{

    make: "Honda",

    model: "CRV",

    year: "2017"

  },

  {

    make: "Toyota",

    model: "Camry",

    year: "2020"

  },

  {

    make: "Chevy",

    model: "Camaro",

    year: "2020"

  }

]


myFilter = [{

    field: "make",

    value: "Chevy",

    type: "string"

  },

  {

    field: "year",

    value: "2020",

    type: "date"

  }

];



// Expected OutPut:

myArray = [{

  make: "Chevy",

  model: "Camaro",

  year: "2020"

}]



var tempArray = [];

const keysToMatch = myFilter.length;

let matchedItems = [];

myArray.forEach((data) => {

  matchedItems = [];

  let itemsToFind = Object.values(data);

  myFilter.forEach((filterItem) => {

    if (itemsToFind.indexOf(filterItem.value) != -1) {

      matchedItems.push("matched");

    }

  });

  //check if everything matched

  if (matchedItems.length === keysToMatch) {

    tempArray.push(data);

  }

});


console.log(tempArray);


慕慕森
浏览 478回答 3
3回答

德玛西亚99

var tempArray = [];const keysToMatch = myFilter.length;let matchedItems = [];myArray.forEach((data) => {    matchedItems = [];    let itemsToFind = Object.values(data);    myFilter.forEach((filterItem) => {        if (itemsToFind.indexOf(filterItem.value) != -1) {            matchedItems.push("matched");        }    });    //check if everything matched    if (matchedItems.length === keysToMatch) {        tempArray.push(data);    }});console.log(tempArray);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答