如何让对象键依赖于同一对象中的另一个键?

How to have an object key depend on another key in the same object?

我有一个非常简单的函数来构建一个对象并记录它。

对象中的一个键应该依赖于另一个键。

我觉得加上代码会更清楚

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,我希望字符串是 "accepted" 如果它是 0,我希望字符串是 "fail" 如果它的 1 我希望字符串是 "success"

因为现在我只是不确定,请帮忙!

谢谢

假设 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 对象。