ES6 数组过滤器删除常见项目

ES6 array filter to remove common items

我正在尝试删除两个数组中 slot_id 的常见出现,并构建一个没有 slot_id.

重复项的对象数组

尝试了以下但其结果是另一个数组内的输出数组,即输出 [Array(0), Array(2)]。我期待如下输出数组。

预期结果

[{
  "_id": "5b55c44038a7701a93fb1a68",
  "end_time": {
    "hours": "01"
  },
  "start_time": {
    "hours": "00"
  }
}, {
  "_id": "5b55c44038a7701a93fb1a67",
  "end_time": {
    "hours": "03"
  },
  "start_time": {
    "hours": "01"
  }
}]

输入数组

Slots = [{
  "_id": "5b55c43532996fec4f500aa5",
  "time_slots": [{
    "_id": "5b55c43538a7701a93fb1a58",
    "end_time": {
      "hours": "01"
    },
    "start_time": {
      "hours": "00"
    }
  }, {
    "_id": "5b55c43538a7701a93fb1a57",
    "end_time": {
      "hours": "03"
    },
    "start_time": {
      "hours": "01"
    }
  }]
}, {
  "_id": "5b55c44032996fec4f500abf",
  "time_slots": [{
    "_id": "5b55c44038a7701a93fb1a68",
    "end_time": {
      "hours": "01"
    },
    "start_time": {
      "hours": "00"
    }
  }, {
    "_id": "5b55c44038a7701a93fb1a67",
    "end_time": {
      "hours": "03"
    },
    "start_time": {
      "hours": "01"
    }
  }]
}]

filterData = [{
  "slot_id": "5b55c43538a7701a93fb1a57",
  "user_id": "5b4dbbf9788bbb4fd01cea33"
}, {
  "slot_id": "5b55c43538a7701a93fb1a58",
  "user_id": "5b4dbbf9788bbb4fd01cea33"
}]

let result = Slots.map(m => m.time_slots.filter(e => !filterData.find(a => e._id == a.slot_id)));

使用Array.prototype.reduce() 连接数组

const Slots = [{"_id":"5b55c43532996fec4f500aa5","time_slots":[{"_id":"5b55c43538a7701a93fb1a58","end_time":{"hours":"01"},"start_time":{"hours":"00"}},{"_id":"5b55c43538a7701a93fb1a57","end_time":{"hours":"03"},"start_time":{"hours":"01"}}]},{"_id":"5b55c44032996fec4f500abf","time_slots":[{"_id":"5b55c44038a7701a93fb1a68","end_time":{"hours":"01"},"start_time":{"hours":"00"}},{"_id":"5b55c44038a7701a93fb1a67","end_time":{"hours":"03"},"start_time":{"hours":"01"}}]}];

const filterData = [{"slot_id":"5b55c43538a7701a93fb1a57","user_id":"5b4dbbf9788bbb4fd01cea33"},{"slot_id":"5b55c43538a7701a93fb1a58","user_id":"5b4dbbf9788bbb4fd01cea33"}];

const result = Slots.map(m => m.time_slots.filter(e => !filterData.find(a => e._id == a.slot_id))).reduce((accumulator, currentValue) => accumulator.concat(currentValue));

document.write('<pre>' + JSON.stringify(result, null, '\t') + '</pre>')