Vegaaaa
Vegaaaa

Reputation: 484

JavaScript use String as parameter for an object key

I have the following problem and am not finding the solution for this since hours.

I have an JSON-object trip. The mongoose-schema looks like this:

var TripSchema = new Schema({
userId: String,
tripToken: String,
busId: Number,
lineId: Number,
tracking: [
    {
        vehicleCurrentStopCode: String,
        vehicleTrackingList: [
            {
                vehicleLatitude: Number,
                vehicleLongitude: Number,
                vehicleUpdateTimestamp: Number,
                vehicleUpdateId: Number
            }
        ],
        userTrackingList: [
            {
                userLatitude: Number,
                userLongitude: Number,
                userUpdateTimestamp: Number,
                vehicleUpdateId: Number
            }
        ]
    }
]
});

Now in my database-handler module I have written a function, which needs to be identified by the trackingList, i.e. if I want to updatethe vehicleTrackingList or the userTrackingList.

Therefore I tried the following:

switch (trackingList.vehicleLatitude) {
case ('number') :
    pushElementInCorrectTrackingList(trip, "vehicleTrackingList", index, trackingList);
    break;
case ('undefined') :
    pushElementInCorrectTrackingList(trip, "userTrackingList", index, trackingList);
    break;
}

With the function:

var pushElementInCorrectTrackingList = function (trip, typeOfTrackingList, index, trackingList) {

trip.tracking[index].typeOfTrackingList.push(trackingList);
...
}

This doesn't work since js awaits to not recieve a String after trip.tracking[index].

But I didn't find any function to convert the String to an object-key. At first I thought that the following would have solved the problem but, I catched the error: TypeError: Cannot call method 'push' of undefined.

var pushElementInCorrectTrackingList = function (trip, typeOfTrackingList, index, newElement) {
var param = typeOfTrackingList.valueOf();
trip.tracking[index].param.push(newElement);
...
}

Does anybody have a solution for this?

Thanks in advance!

Upvotes: 0

Views: 75

Answers (1)

progsource
progsource

Reputation: 639

Did you try this already?

var pushElementInCorrectTrackingList = function (trip, typeOfTrackingList, index, trackingList) {
trip.tracking[index][typeOfTrackingList].push(trackingList);
    ...
}

Upvotes: 1

Related Questions