Seb
Seb

Reputation: 3215

Failed to concat JSON into a JSON Array

I am trying to create a JSON array by randomly selecting JSON object but the JSON array is empty.

I checked that my random function works and it grabs a JSON and it's the case


static getNearbyClasses(nb_class) {
        var jsonClasses = JSON.parse(JSON.stringify(ClassDetailsData.Classes));
        var nearbyClasses = []
        for(let k=0; k < nb_class; k++){
            var randomnb = Utils.getRandomInt(jsonClasses.length-1)
            var randomClass = jsonClasses[randomnb]
            console.log("-----" + randomnb + "---------")
            console.log(randomClass)
            nearbyClasses.concat(randomClass)
        }
        console.log(nearbyClasses)
        return nearbyClasses
    }

but nearbyClasses is still null. randomClass always have a JSON object

Any idea ? Thanks

Upvotes: 1

Views: 66

Answers (2)

Brad
Brad

Reputation: 163478

An alternative to the selected answer, if you don't want a new array is to use .push():

nearbyClasses.push(...randomClass);

Upvotes: 1

Sven.hig
Sven.hig

Reputation: 4519

concat doesn't change the original array but returns a new array after merging them.

So in this line:

nearbyClasses.concat(randomClass);

The new returned array by concat is not assigned to nearbyClasses and nearbyClasses will not be changed.

To fix this just change it to:

nearbyClasses = nearbyClasses.concat(randomClass);

Upvotes: 2

Related Questions