过滤JS多维数组

时间:2018-04-10 21:42:29

标签: javascript arrays dictionary filter

我正在尝试过滤一些事件及其相应的时段。数据结构如下:

var items = [
  {
    title: 'Category Title',
    events: [
      {
        title : '1:00pm',
        category : 1
      },
      {
        title: '2:00pm',
        category : 2
      }
    ]
  },
  {
    title: 'Category Title 2',
    events: [
      {
        title : '3:00pm',
        category : 1
      },
      {
        title: '4:00pm',
        category : 2
      }
    ]
  }
];

我想按类别过滤事件。我尝试过使用过滤器/地图,但似乎无法弄明白。例如,如何过滤列表以仅返回类别为1的项目?

5 个答案:

答案 0 :(得分:1)

您可以使用过滤器来获取缩减列表,但您可以通过其他方式执行此操作,例如reduce。

  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter   



var items = [
  {
    title: 'Category Title',
    events: [
      {
        title : '1:00pm',
        category : 1
      },
      {
        title: '2:00pm',
        category : 2
      }
    ]
  },
  {
    title: 'Category Title 2',
    events: [
      {
        title : '3:00pm',
        category : 1
      },
      {
        title: '4:00pm',
        category : 2
      }
    ]
  }
];
let cat1, cat2;
items.forEach(item => {
  cat1 = item.events.filter(item => item.category === 1)
  cat2 = item.events.filter(item => item.category === 2)
})


console.log(cat1, cat2)




继续更高级你可以给函数一个你想要的类别数组,它将返回一个对象,其中包含所有类别的键和它们内部的事件。希望这可以帮助。



var items = [
      {
        title: 'Category Title',
        events: [
          {
            title : '1:00pm',
            category : 1
          },
          {
            title: '2:00pm',
            category : 2
          }
        ]
      },
      {
        title: 'Category Title 2',
        events: [
          {
            title : '3:00pm',
            category : 1
          },
          {
            title: '4:00pm',
            category : 2
          }
        ]
      }
    ];
    
    function filter(cat, arr) {
      return arr.filter(i => i.category === cat);
    }
    function getCategorys(category) {
      return items.reduce((prev, curr) => {
         category.forEach(cat => {
         !prev[cat] ? prev[cat] = [] : null;
         prev[cat] = [...filter(cat, curr.events), ...prev[cat]];
         })
         return prev;
      }, {})
    }
    
    console.log(getCategorys([1,2]))




答案 1 :(得分:1)

您可以使用函数filter和函数some来获取数组events中具有特定类别的项目。

此示例包含一个事件数组包含category === 3

的项目

var items = [  {    title: 'Category Title',    events: [      {        title : '1:00pm',        category : 1      },      {        title: '2:00pm',        category : 2      }    ]  },  {    title: 'Category Title 2',    events: [      {        title : '3:00pm',        category : 1      },      {        title: '4:00pm',        category : 2      }    ]  },  {    title: 'Category Title 3',    events: [      {        title : '3:00pm',        category : 1      },      {        title: '4:00pm',        category : 3      }    ]  }],
    cat = 3,
    result = items.filter(o => o.events.some(({category}) => cat === category));

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

如果您只需要使用category === 3的事件,请使用reduce函数:

var items = [  {    title: 'Category Title',    events: [      {        title : '1:00pm',        category : 1      },      {        title: '2:00pm',        category : 2      }    ]  },  {    title: 'Category Title 2',    events: [      {        title : '3:00pm',        category : 1      },      {        title: '4:00pm',        category : 2      }    ]  },  {    title: 'Category Title 3',    events: [      {        title : '3:00pm',        category : 1      },      {        title: '4:00pm',        category : 3      }    ]  }],
    cat = 3,
    result = items.reduce((a/*Accumulator*/, o/*Current object in array*/) => { 
      // 1. We get the events with a specific category  (In this case -> 3)
      var filtered = o.events.filter(({category}) => cat === category);
      
      // 2. If the previous filter returns at least one event, we need to push
      //    the current object 'o' with the filtered events.
      if (filtered.length) { // if length !== 0 we need to push the object.
        // 3. We use Object.assign to avoid any mutation over the original object.
        //    So, basically we create a new object with the original properties
        //    and finally we assign the filtered events to the property events.
        a.push(Object.assign({}, o, {events: filtered}));
      }
      
      return a;
    }, []/*Initial value (this array will contain the filtered objects)*/);

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

答案 2 :(得分:0)

您可以使用以下功能获得所需的结果:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

function filterByCategory(items, category) {
    return items.reduce((events, i) => {
        const filteredEvents = i.events.filter(e => e.category === category);
        if (filteredEvents) {
            return events.concat(filteredEvents);
        }
        return events;
    }, []);
}

答案 3 :(得分:0)

这里你应该做的是使用 Array.filter() method 根据子items数组过滤你的events数组,你可以用它来测试 Array.some() 可以找到category===1

var filteredResults = items.filter(function(item) {
  return item.events.some(e => e.category === 1);
});

<强>演示:

var items = [{
    title: 'Category Title',
    events: [{
        title: '1:00pm',
        category: 1
      },
      {
        title: '2:00pm',
        category: 2
      }
    ]
  },
  {
    title: 'Category Title 2',
    events: [{
        title: '3:00pm',
        category: 1
      },
      {
        title: '4:00pm',
        category: 2
      }
    ]
  }
];

var result = items.filter(function(item) {
  return item.events.some(e => e.category === 1);
});


console.log(result);

答案 4 :(得分:-1)

function hasCategory(item, cat) {
    for(e in item.events){
    if(item.events[e].category === cat) {
       return true;
     break;
    }
   }
   return false;
}

var filtered = items.filter((item) => {
    return hasCategory(item, 2);
});

console.log(filtered);