我正在尝试删除两个数组中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)));
答案 0 :(得分:3)
使用Array.prototype.reduce() concat数组
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>')