如何拥有对象键取决于同一对象中的另一个键?

时间:2019-04-10 15:39:35

标签: javascript enumerate

我有一个非常简单的函数,可以构建一个对象并将其记录下来。

对象中的一个键应取决于另一个键。

我认为添加代码后会更加清晰

module.exports = function (information) {

    var numObj = {
        [-1]: "accepted",
        [0]: "fail",
        [1]: "success"
    }
    console.log(numObj)

    var ip = require('ip');
        var logObj = {
            UUID: information.UUID, // get from outside
            FN_TIME_STAMP: information.FN_TIME_STAMP, // not sure if necessary
            FN_CORRELATION_ID: information.FN_CORRELATION_ID,// get from outside
            FN_REF_ID: information.FN_REF_ID, //get from outside
            FN_METHOD_NAME: "docToMail", // constant
            FN_STATUS_CODE: information.FN_STATUS_CODE, //get from outside
            FN_STATUS_DESC: numObj[this.FN_STATUS_CODE], // depends on FN_STATUS_CODE
            FN_DOC_ID: information.FN_DOC_ID, //get from outside
            FN_USER_NAME: "", // empty for now, probably un-necessary
            FN_APP_ID: information.FN_APP_ID, //get from outside
            FN_RMT_ADDRS: ip.address(),//ip address of local machine
            FN_NUM_OF_RETRIES: information.FN_NUM_OF_RETRIES, // get from outside
            FN_FILETYPE: information.FN_FILETYPE, // get from outside
            FN_REC_STATE: numObj[this.FN_STATUS_CODE] //depends on FN_STATUS_CODE
        }
        console.log(logObj)
}

我只希望FN_REC_STATE和FN_STATUS_DESC是取决于FN_STATUS CODE的字符串。 如果它为-1,则我希望该字符串被“接受” 如果它为0,我希望字符串为“ fail” 如果其值为1,则我希望字符串为“成功”

截至目前,我只是不确定,请帮忙!

谢谢

1 个答案:

答案 0 :(得分:2)

假设information.FN_STATUS_CODE-101,则以下解决方案应该有效。

如果您更改

FN_REC_STATE: numObj[this.FN_STATUS_CODE]

FN_REC_STATE: numObj[information.FN_STATUS_CODE]

然后将正确的值放入FN_REC_STATE

这是因为在评估故障线路时,尚未定义this.FN_STATUS_CODE

您还应该更改FN_STATUS_DESC的定义。

此外,您可能会误解this在该函数上下文中的含义。它实际上是指全局对象,而不是logObj对象。