I'm trying to filter data from the response and remove duplicate items and push the data into an array, my api response goes as below:
{
"_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":{
"_id":"100",
"booking_id":"BK163041494",
},
"blocked_thru":"booked",
"dates":"2017-08-30T00:00:00.000Z",
}
From the above response, if "booking_id" exist in object and "booking_id._id" is same then, I need to filter and push only unique objects to array.
I need a response as below:
{
"_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",
},
Any Help would be Appreciated. Thanks.
You can use array#reduce
and array#some
var response =[{"_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":{"_id":"100","booking_id":"BK163041494",},"blocked_thru":"booked","dates":"2017-08-30T00:00:00.000Z",}];
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);
Use Array.prototype.reduce
and a hashtable
to pick out the unique elements - see demo below:
var object=[{"_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":{"_id":"100","booking_id":"BK163041494",},"blocked_thru":"booked","dates":"2017-08-30T00:00:00.000Z",}];
var result = object.reduce(function(hash){
return function(p, c) {
if(!c.booking_id || (c.booking_id && !hash[c.booking_id.booking_id])) {
if(c.booking_id)
hash[c.booking_id.booking_id] = true;
p.push(c);
}
return p;
};
}(Object.create(null)),[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With