我正在尝试从响应中过滤数据并删除重复项并将数据推送到数组中,我的api响应如下:
{
"_id":"0","yacht_id":"200","promo_id":"300","blocked_thru":"promotions","dates":"2017-08-23T00:00:00.000Z",},{
"_id":"1","booking_id":{
"_id":"100","booking_id":"BK163041494","blocked_thru":"booked","dates":"2017-08-30T00:00:00.000Z",{
"_id":"2",}
从上面的响应中,如果对象中存在“booking_id”并且“booking_id._id”相同,那么我需要过滤并仅将唯一对象推送到数组.
我需要回复如下:
{
"_id":"0",
任何帮助,将不胜感激.谢谢.
最佳答案
您可以使用array#reduce和array#some
原文链接:https://www.f2er.com/js/429192.htmlvar response =[{"_id":"0",{"_id":"1","booking_id":{"_id":"100",{"_id":"2",}];
var unique = response.reduce((res,obj) => {
let isFound = res.some(o =>
o['booking_id'] && o['booking_id']['_id'] === obj['booking_id']['_id'] );
if(!isFound) {
res.push(obj);
}
return res;
},[]);
console.log(unique);