如何过滤包含对象的数组数据?

时间:2019-03-15 07:27:26

标签: javascript

这是我的数据:

const sectionDummy = [
  { floor: '1', data: ['A', 'B', 'C']},
  { floor: '2', data: ['D', 'E', 'F']},
  { floor: '3', data: ['G', 'H', 'I']},
];

我可以过滤掉地板并获得正确的数据:

let filterData = [];
filterData = sectionDummy.filter(item => {
  if (item.floor !== undefined) {
    return item.floor.trim().toLowerCase().indexOf(inputValue) >= 0; 
  }
  return {};
});

如果inputValue为1,我将获得返回数据

console.log(filterData); // [{ floor: 1, data: ['A', 'B', 'C']}]

如果我也想过滤数据,我就会陷入困境。

我尝试使用地图

let filterData = [];
filterData = sectionDummy.filter(item => {
  if (item.floor !== undefined) {
    item.data.map((value, index) => {
      if(value.trim().toLowerCase().indexOf(inputValue) >=0) {
        return value;
      } else {
        return {};
      }
    });
  }
  return {};
});

看起来过滤器和地图数据返回不同,所以它不起作用。

如何同时过滤floordata array

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您要先按底限再过滤数据吗?

const sectionDummy = [
  { floor: 1, data: ['A', 'B', 'C']},
  { floor: 2, data: ['D', 'E', 'F']},
  { floor: 3, data: ['G', 'H', 'I']},
];

const floorFilter = 2;
const dataFilter = 'E';

const filteredData = sectionDummy
  .filter(item => item.floor === floorFilter)
  .map(({floor, data}) => ({floor, data: data.filter(d => d === dataFilter)}));
  
console.log(filteredData); //[ { floor: 2, data: [ 'E' ] } ]

还是按地板和数据?

const sectionDummy = [
  { floor: 1, data: ['A', 'B', 'C']},
  { floor: 2, data: ['D', 'E', 'F']},
  { floor: 3, data: ['G', 'H', 'I']},
];

const floorFilter = 2;
const dataFilter = 'E';

const filteredData = sectionDummy
  .filter(({floor, data}) => floor === floorFilter && data.some(d => d === dataFilter))
  
console.log(filteredData) // [ { floor: 2, data: [ 'D', 'E', 'F' ] } ]

答案 1 :(得分:1)

您可以像这样使用reduce:如果searchTextfloor匹配,则返回整个section。否则,如果searchText中存在data,则返回带有过滤后的data数组的节对象。

const sectionDummy = [
  { floor: "1", data: ['A', 'B', 'C']},
  { floor: "2", data: ['D', 'E', 'F']},
  { floor: "3", data: ['G', 'H', 'I']},
];

const filter = (sections, searchText) => {
  searchText = searchText.trim().toLowerCase();
  
  return sections.reduce((acc, { floor, data }) => {
    if (floor === searchText) {
      acc.push({ floor, data })
    } else {
      const filtered = data.filter(d => d.toLowerCase().includes(searchText))
      if (filtered.length > 0)
        acc.push({ floor, data: filtered })
    }

    return acc;
  }, [])
}

console.log(filter(sectionDummy, "A"))
console.log(filter(sectionDummy, "G"))
console.log(filter(sectionDummy, "1"))

答案 2 :(得分:1)

您可以通过检查floorinputValue进行过滤,并将两个值相等的对象作为对象。

let filterData = searchBuildings.filter(({ floor }) => floor === inputValue);