编辑代码

const a = {
    "inCommStatus": 0,
    "initStatus": 0,
    "state": 1,
    "InvalidTokenBox": {"attachStatus": 0, "containerStatus": 0, "getSensorFull": 0},
    "SaleTokenBox": {"attachStatus": 0, "containerStatus": 0, "getSensorEmpty": 0},
    "accidentStatus": 0, "containerStatus": 1, "deviceType": "CST", "enable": true,
    "extraSaleTokenBox": {"attachStatus": 0, "containerStatus": 2, "getSensorEmpty": 1},
}
const MeaningStrMap = {
    containerStatus: ["正常", "将空", "空", "将满", "已满"],
    attachStatus: ["已安装", "未安装"],
    getSensorFull: ["否", "是"],
    getSensorEmpty: ["否", "是"],
    enable: ["否", "是"],
    accidentStatus: ["正常", "警告", "异常"],
    state: ["正常", "警告", "故障", "禁用"],
}

const MeaningMap = {
    state: '综合服务状态',
    deviceType: '设备类型',
    enable: '开启状态',
    inCommStatus: '连接状态',
    initStatus: '初始化状态',
    containerStatus: '容器容量状态',
    accidentStatus: '异常状态',
    attachStatus: '安装状态',
    getSensorFull: '传感器报满',
    getSensorEmpty: '传感器报空',
    errMsg: '报错信息',
    SaleTokenBox: '票箱1',
    extraSaleTokenBox: '票箱2',
    InvalidTokenBox: '回收箱2', // sma设置为 回收箱2
    RecoveryTokenBox: '回收箱1',
    DispBox: '备用钱箱1', // bc设置为 找零钱箱1
    extraDispBox: '备用钱箱2',// bc设置为 找零钱箱2
    AcceptBox: '接受箱',
    RecycleBox: '硬币循环箱',
}

const adjustMeaningMap = (deviceType) => {
    if (deviceType === 'BC') {
        MeaningMap.DispBox = '找零钱箱1'
        MeaningMap.extraDispBox = '找零钱箱2'
    } else if (deviceType === 'SMA') {
        MeaningMap.InvalidTokenBox = '回收箱2'
    } else { // 恢复默认映射
        MeaningMap.DispBox = '备用钱箱1'
        MeaningMap.extraDispBox = '备用钱箱2'
        MeaningMap.InvalidTokenBox = '回收箱2'
    }
}

const getMeaningStr = (key, parentKey = '') => {
    let res = ''
    if (typeof key === 'object' && key !== null) {
        res += parentKey ? '{' : ''
        Object.entries(key).forEach(([key, value]) => {
            const meaningKey = MeaningMap[key]
            const childResult = getMeaningStr(value, key)

            if (childResult)
                res += `${meaningKey}:${childResult}, `
        })
        res = res.slice(0, -2)
        res += parentKey ? '}' : ''
    } else if (typeof key === 'boolean')
        res = MeaningStrMap[parentKey][+key]
    else if (typeof key === 'number' && MeaningStrMap[parentKey])
        res = MeaningStrMap[parentKey][key]

    return res
}

adjustMeaningMap(a.deviceType)
console.log(getMeaningStr(a))