wtblife wtblife - 3 months ago 9
Javascript Question

Arrow function error: Object is not a function

When I try to use an arrow function with {} it seems to think it's an object and throw an error. I thought this is how arrow functions are generally defined?

The error given for the code below is

TypeError: #<Object> is not a function


let allProperties = [];

sites.forEach(site => site.properties.forEach(p => {if (!allProperties.find(p)) allProperties.push(p)} ));


Edit: sites might be defined similarly to the following:

sites = [
{
"properties": [
{ "id": "111-11", "display": "Zone", "value": 1 },
]
}];

Answer

It's barking at if(!allProperties.find(p)). It's not liking the .find() because you have supplied it with an object as a parameter, not a function. .find() Docs Here

If you change it to if (allProperties.indexOf(p) === -1) {...} it works as expected.

var allProperties = [];
var sites = [
{
    "properties": [
        { "id": "111-11", "display": "Zone", "value": 1 },
    ]
}];

sites.forEach(site => site.properties.forEach(p => {
	if (allProperties.indexOf(p) === -1) {
		allProperties.push(p);
	}
}));

console.log(allProperties);

Comments