0

I have a class with an array of object.

export interface Filter {
  sf?:Array<{key:string,value:string}>;
}

I try to use forEach function to loop and log each object value inside the array.

f : Filter = {sf:[{key:'a',value:'b'},{key:'c',value:'d'}]}; 

f.sf.forEach(element => {
  console.log(element.key);
});

However error appears inside the mongo db server.

[error] f.sf.forEach is not a function 0
node                           | TypeError: f.sf.forEach is not a function

how can I fix this error so the forEach works? thank you.

1
  • Could it be that f.sf is undefined as permitted by the Filter interface definition? Commented Dec 15, 2022 at 9:28

1 Answer 1

1

As stated by your Filter interface, sf is optional.

Optional values will default to undefined (unless otherwise stated). You can check if a variable is not defined in many ways:

const myVariable = undefined
const myOtherVar = null

// double "=", not always a great way to test the value
console.log("myVariable, ==", myVariable == undefined)
console.log("myVariable, ===", myVariable === undefined)

console.log("myOtherVar ==", myOtherVar == undefined
console.log("myOtherVar ===", myOtherVar === undefined

Note how undefined == null is true but undefined === null is false

You either need to make it non-optional like so:

export interface Filter {
  sf:Array<{key:string,value:string}>;
}

Another way of writing this is:

type SF = {
  key:string,
  value:string
}

interface Filter {
  sf: SF[];
}

Or use optional chaining like this:

f.sf?.forEach(element => {
  console.log(element.key);
});
Sign up to request clarification or add additional context in comments.

5 Comments

After trying the optional chaining, it returns error TypeError: _a.forEach is not a function...
Hi I also added a if(f.sf!=null) statement outside the forEach function, since my post's edit function is bug, I want to tell you this addition info here. Hope it is useful.
I also checked the object with function Array.isArray(f.sf), seems like it is false...
@AkiZukiLenn Optional objects will default to undefined, not necessarily null. null and undefined can be tricky, because: undefined != null // false BUT undefined !== null // true. Also if you got _a.forEach is not a function then you have the same optional issue for the variable a (Provided a is an optional array too)
Found the problem, its outside of this topic scope. Turns out angular form.value do not return array, its an object. Have to map it back into an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.