gpt4 book ai didi

javascript - 如何过滤数组中的不同键并在angular js中获得唯一结果

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:29 24 4
gpt4 key购买 nike

我正在尝试从响应中过滤数据并删除重复项并将数据推送到数组中,我的 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":{
"_id":"100",
"booking_id":"BK163041494",
},
"blocked_thru":"booked",
"dates":"2017-08-30T00:00:00.000Z",
}

从上面的响应来看,如果“booking_id”存在于对象中并且“booking_id._id”相同,那么我需要过滤并仅将唯一对象推送到数组。

我需要如下回复:

{
"_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",
},

任何帮助将不胜感激。谢谢。

最佳答案

您可以使用array#reducearray#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);

关于javascript - 如何过滤数组中的不同键并在angular js中获得唯一结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com