简体   繁体   English

JavaScript使用String作为对象键的参数

[英]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 . 我有一个JSON对象旅行 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, ie if I want to updatethe vehicleTrackingList or the userTrackingList . 现在,在我的数据库处理程序模块中,我编写了一个函数,该函数需要由trackingList标识,即,如果我想更新vehicleTrackingListuserTrackingList

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]. 这是行不通的,因为js等待trip.tracking [index]后不接收字符串。

But I didn't find any function to convert the String to an object-key. 但是我没有找到任何将String转换为对象键的函数。 At first I thought that the following would have solved the problem but, I catched the error: TypeError: Cannot call method 'push' of undefined . 起初,我认为以下方法可以解决问题,但我发现了错误: TypeError:无法调用undefined的方法“ push”

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! 提前致谢!

Did you try this already? 你已经尝试过了吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM