Home > Enterprise >  Error: Response is not a function, when trying to find if the name exists
Error: Response is not a function, when trying to find if the name exists

Time:07-11

So I'm using mongodb to fetch some data from the database.

The issue is when I try to check for something in an array

Here is what the structure looks like:

Example array structure

{ // ...
    likedPeople: [
        {
            name: "foo"
            image: "test",
        },
        {
            name: "bar",
            image: "baz",
        }
    ]
}

This is the array i get Back.

So when i try to find if it includes a certain value, eg:


const displayName = "foo";

console.log(
    likedPeople.map((likedPerson) => {
      return likedPerson.name === displayName; // Output: [true, false]
    })
  );

But then If i again try to do some other method on it like map() or includes(), It breaks the setup:

const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function

But the fact is that I am getting an array with the values, so what am I even doing wrong here?

I tried adding an optional chaining response?.map() but still it gave me the same error.

Also the includes() method also returns me the same response.includes is not a function error.

Can anyone help?

CodePudding user response:

Use the some method to check the name exists in likedPeople :

const likedPeople = [
    {
        name: "foo",
        image: "test",
    },
    {
        name: "bar",
        image: "baz",
    }
];
    
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)

  • Related