Carlos Fernandez
Carlos Fernandez

Reputation: 9

Error while checking if an array contains an object

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

Upvotes: 0

Views: 43

Answers (2)

Hao Wu
Hao Wu

Reputation: 20734

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);
    }
};

Upvotes: 1

JSmart523
JSmart523

Reputation: 2497

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.

Upvotes: 0

Related Questions