Home > Net >  Push multiple objects in an new array makes array element type undefined
Push multiple objects in an new array makes array element type undefined

Time:09-17

I used API call get JSON data, filter it and pushing objects into an new array. However, the array elements is undefined type instead of object.

async function getData() { // HTTP get request, API call

    try {
        let response = await fetch(dataURL)
        let data = await response.json();

        return data;

    } catch (error) {
        console.log(error);
    }    

}

function filterDataAtSource(city, vacTypeFilters) {

    var filteredFeatures = [];

    getData().then(function(geojson) {
        var features = geojson.features
                 
        features.forEach(element => {
                                       
            if (element.properties.City === city) {
                console.log("type of element :", typeof(element));
                filteredFeatures.push(element);
            }
        }); 

    })

    console.log("typeof child:", typeof(filteredFeatures[0])); /* undefined type here */

}

CodePudding user response:

You are working with asynchronous code and need to connect in to the promise chain to avoid looking at the variable value too early.

Something like this might work better:

function filterDataAtSource(city, vacTypeFilters) {        
    // return the promise
    return getData().then(function(geojson) {
        var filteredFeatures = [];
                    
        geojson.features.forEach(element => {                                           
            if (element.properties.City === city) {
                console.log("type of element :", typeof(element));
                filteredFeatures.push(element);
            }
        };

        // return this to minimize visibility
        return filteredFeatures;
     }); 
});

filterDataAtSource('Paris', {})
    .then((filteredFeatures) => {
        console.log("typeof child:", typeof(filteredFeatures[0]));
    });

And you can play around with the factoring of the code by using async functions. For example:

const filterDataAtSource = async (city, vacTypeFilters) =>
    (await getData())
        ?.features
        ?.filter(({ properties: { City } }) => City === city)

// ensure you are in an async function, or an environment that supports global async
const filteredFeatures = await filterDataAtSource('Paris', {})
console.log("typeof child:", typeof(filteredFeatures[0]));

CodePudding user response:

You add values to the array only by condition element.properties.City === city Are you sure that the condition is met at least once? Have you checked the length of the array filteredFeatures at the output?

undefined can be for the simple reason that there is no 0 element in the array

CodePudding user response:

You are retrieving values before they exist because of calling an asynchronous function.

You could try this also. Make filterDataAtSource() asynchronous to await getData().

async function filterDataAtSource(city, vacTypeFilters) {
    var filteredFeatures = [];
    const geojson = await getData();
    console.log("typeof child:", typeof(filteredFeatures[0])); /* undefined type here */
    
    var features = geojson.features;
             
    features.forEach(element => {     
        if (element.properties.City === city) {
            console.log("type of element :", typeof(element));
            filteredFeatures.push(element);
        }
    });
}
  • Related