通过其他数组的索引过滤数组的对象

时间:2018-03-14 09:18:44

标签: javascript arrays typescript array-filter

我有一个场景,用户可以多选项并删除它们,所以我有两个数组:

  1. 使用复选框值(已选中和索引)
  2. 需要根据选中的值索引进行过滤的实际项目。
  3. 这里有两个数组和使用lodash的预期结果。

    const checked = [
      {
        index: 0,
        checked: false
      },
      {
        index: 1,
        checked: true //note second index is checked so we need to filter out second index from items array.
      },
    ];
    
    const items = [
      {
        title: 'This is title 1',
        description: 'This is description 1',
        end_date: '2018-03-12 14:00:00',
        location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
        room: 401,
        start_date: '2018-03-12 13:00:00',
      },
      {
        title: 'This is title 2',
        description: 'This is description 2',
        end_date: '2018-03-12 14:00:00',
        location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
        room: 401,
        start_date: '2018-03-12 13:00:00',
      }
    ];
    
    
    const result = [
      {
        title: 'This is title 1',
        description: 'This is description 1',
        end_date: '2018-03-12 14:00:00',
        location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
        room: 401,
        start_date: '2018-03-12 13:00:00',
      }
    ];
    

2 个答案:

答案 0 :(得分:1)

您只需要使用filter函数并获取当前对象的索引。然后使用此索引访问已检查数组的n-th项(我在checked数组中提供此解决方案原因可见您的数组包含所有复选框的状态 - 已检查并且未选中)并检查它的checked属性。



const checked = [
  { index: 0, checked: false },
  { index: 1, checked: true }
];

const items = [
  {
    title: 'This is title 1',
    description: 'This is description 1',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  },
  {
    title: 'This is title 2',
    description: 'This is description 2',
    end_date: '2018-03-12 14:00:00',
    location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
    room: 401,
    start_date: '2018-03-12 13:00:00',
  }
];

const filtered = items.filter((item, index) => !checked[index].checked);

console.log(filtered);




答案 1 :(得分:0)

你可以这样做。

var result=[];
checked.forEach(function (item) {
    if(item.checked)
    {
        result.push(items[item.index]);
    }
})

console.log(result);
相关问题