Home > Software engineering >  Error while checking if an array contains an object
Error while checking if an array contains an object

Time:09-09

I am having this problem, I am trying to check if an object is inside an array but it is telling me that it is false, when in fact it should be true.

const checkfileExist = (docType, obj) => {
    if (docType === "COC") {
      let cocArray = JSON.parse(dbData[0].COC);
      console.log("COC DATA", cocArray);
      console.log("OBJ DATA", obj);
      console.log(cocArray.includes(obj));
    }
  };

enter image description here

CodePudding user response:

At the end of the if block, try inserting

obj.cow = 'moo':
console.log({cocArray, obj});

My guess is that property moo will appear as added to obj but not cocArray[0] because despite having the same values they are actually different objects.

CodePudding user response:

cocArray is an array of objects that parsed from a string, although the object it contains looks exactly the same as obj, but they are completely different references. Thus cocArray.includes(obj) will aways return false.

You need to manually detect whether an object has the same key value pairs as another, such as:

const checkfileExist = (docType, obj) => {
    if (docType === "COC") {
        let cocArray = JSON.parse(dbData[0].COC);
        console.log("COC DATA", cocArray);
        console.log("OBJ DATA", obj);

        const isExist = cocArray.some(item => Object.entries(obj).every(([key, value]) => item[key] === value));
        console.log(isExist);
    }
};
  • Related