#how to use this array foreach correctly?

12 messages · Page 1 of 1 (latest)

oak violet
#

im currently trying to do an foreach loop, but seems not to work.. any solutions (sorry for my english pumpkinhehe)
thank you for help! :)

Code:

const mapParts = {
    "MapPart1": {
        vertices: [
            new Vector3(-1090.255, -1714.1018, 4.3393965), 
            new Vector3(-1001.314, -1611.5155, 4.929909)
        ]
    }
}

addGameEvent("InitGameEvent", () => {
    Array.from(mapParts).forEach(element => {
          // element is null :(
    });
});
sonic roost
#

The error in the code you provided is that Array.from() is being used on an object, rather than an array. Array.from() is a method that creates a new array from an array-like or iterable object, but it does not work on objects that are not array-like or iterable. In this code, mapParts is an object that contains properties with values, but it does not have any array-like or iterable structure, so Array.from() cannot be used on it.

To fix this error, you can either convert mapParts to an array before using Array.from() on it, or you can use a regular for loop to iterate over the properties of the object, like this:

oak violet
#

Okay, it seems to work - but how can i access 'vertices' then? element.vertices is undefined then :D

#

element is return "MapPart1", but element.vertices is returning undefined

#

im mostly scripting in C#, but for my new project i need javascript, never worked that much with it

sonic roost
#

If you are using a regular for loop to iterate over the properties of an object, you can access the values of those properties by using the property names as keys. In the code you provided, mapParts is an object that contains properties with values, but it does not have any array-like or iterable structure, so Array.from() cannot be used on it.

To access the vertices property of each element in the mapParts object, you can use the property name as a key, like this:

#

This code uses a regular for loop to iterate over the properties of the mapParts object, and it uses the property name as a key to access the values of each property. This code will not produce an error, and it will allow you to access the vertices property of each element in the mapParts object.

oak violet
#

Ahh, remember again - thank you very much! :)

sonic roost
#

It works right?

oak violet
#

Yep