防止在数组中添加重复值

时间:2021-07-14 02:57:56

标签: javascript html jquery arrays ajax

我正在运行此代码并调用 ajax 请求 20 次。如果数组中不存在相同的记录,我想将 ajax 响应添加到数组中。我正在这样做,但它也在添加重复数据。我在这方面做错了什么? 我也试过使用 indexOf 但这似乎也不起作用

有什么办法可以在每次循环运行时跳过具有相同 ID 的对象吗?

例如,如果我得到 CID 28 的 api 响应,如果 CID 28 再次出现,我会跳过该对象添加到数组。

for(let i = 0; i< 20; i++){
                $.ajax({
                    url: "/bin/adp/rest_api_response.megtile.json",
                    method: "POST",
                    "data": { "session": sessionID, "WIN_NBR": win, "local_time": localT.toString(), "network": "on" },
                    beforeSend: function (xhr) {

                    },
                    success: function (data) {

                        urls = data.btn_link;
                        var tmp_thumbnail = "url('" + data.image + "')"
                        thumbnails = tmp_thumbnail;
                        descriptions = data.banner_text;
                        btn_txt = data.btn_text;
                        titles = data.banner_title;
                        cid = data.CID;

                        console.log("datttt",arr)
                        console.log("dddd",data)
                        if (arr.includes(data) === false) {
                            arr.push(data);                        
                        }
                        
                    }
                });
            }

API Response
{
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
}

Duplicate API response

{
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
}

API another response
{
    "CID": "CID3",
    "btn_link": "https://get.com/automatic",
    "btn_text": "Learn more",
    "campaign_title": "Even App",
    "banner_text": "",
    "banner_title": "Get automatic access to your earned wages every week",
    "image": "/content/uswire/en_us/me/campaigns/even-app/jcr:content/par/hero_v2_copy_cpy.g.jpeg",
    "link": "",
    "request_ID": "ae5e5396-0317-4ec8-b7b1-9f0deef5cd"
}

4 个答案:

答案 0 :(得分:1)

由于您尝试在对象数组中搜索对象,因此请使用自定义函数进行对象比较。下面添加我的实现方式。

const responseObj = {
  "CID": "CID28",
  "btn_link": "https://one.xyz.com",
  "btn_text": "Visit page",
  "campaign_title": "RFL Talkspace",
  "banner_text": "Talk to a licensed, professional therapist. ",
  "banner_title": "Talking about it can help.",
  "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
  "link": "",
  "request_ID": "fa9a925b-f882-410-558-761e179eb227"
};
const responseArr = [];
responseArr.push(responseObj);
const responseObjNew = { ...responseObj };

// Using Includes method
console.log('Using array.includes', responseArr.includes(responseObjNew));

// Using Custom defined function
console.log('Using custom functon', containsObject(responseObjNew, responseArr));

// Updating Object
responseObjNew.CID = "CID13";

// Checking with updated object
console.log('Using custom functon', containsObject(responseObjNew, responseArr));

function containsObject(obj, list) {
  var isFound;
  for (let index = 0; index < list.length; index++) {
    isFound = compareObjects(obj, list[index]);
    if(isFound) {
      // Matching Object Found: EXIT
      index = list.length;
    }
  }
  return isFound;
}
function compareObjects(obj1, obj2) {
  var isMatch = Object.keys(obj1).length === Object.keys(obj2).length;
    if (isMatch) {
      Object.keys(obj1).forEach((key) => {
        isMatch = isMatch && obj1[key] === obj2[key]
      })
    }
    return isMatch
}

答案 1 :(得分:0)

这是一个例子来证明我所说的:

let a={
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
};
let b={
    "CID": "CID28",
    "btn_link": "https://one.xyz.com",
    "btn_text": "Visit page",
    "campaign_title": "RFL Talkspace",
    "banner_text": "Talk to a licensed, professional therapist. ",
    "banner_title": "Talking about it can help.",
    "image": "/content/dam/us-wire-wm1/images/me@/campaigns/campaigns-2021/may/talkspace.png",
    "link": "",
    "request_ID": "fa9a925b-f882-410-558-761e179eb227"
};
let arr=[JSON.stringify(a)];
let arr1=[a];
console.log("using the stringify method:"+arr.includes(JSON.stringify(b)));
console.log("without using the stringify method:"+arr1.includes(b));

答案 2 :(得分:0)

如果,正如您自己已经提到的,可以通过具有相同的 id 来识别“相同”响应,那么您可以通过使用对象而不是数组来保存从 AJAX 接收到的数据来简化比较调用:

// somewhere at the top:
var obj={}; // global variable

// then, within your AJAX-related code:
// ...
cid = data.CID

if (!obj[cid]) obj[cid]=data;

如果您想以数组的形式访问结果,您总是可以通过执行

obj 中提取它
arr = Object.values(obj);

答案 3 :(得分:0)

为什么不在创建数组后直接处理它?<​​/p>

  const people = [
     { id: 1, firstName: "John", secondName: "Smith"}
     { id: 7, firstName: "Jack", secondName: "Foster"},
     { id: 7, firstName: "Jack", secondName: "Foster"},
     { id: 7, firstName: "Jack", secondName: "Foster"}
];

然后只需使用 helprjs 为您解决问题。

removeDuplicates(people, "id");
// [{ id: 1, firstName: "John", secondName: "Smith"}]

试试这里的demo