如何在JavaScript对象的深处编辑特定值?

时间:2019-01-18 11:03:28

标签: javascript node.js object ecmascript-6

我在节点中有以下JavaScript对象:

that.responseData = {
    fields: {
        id: {
            label: 'ID',
            value: objectRecord.id,
            info: '',
            example: '',
            required: false,
            errorStatus: '',
            errorMessage: ''
        },
        title: {
            label: 'Title',
            value: objectRecord.title,
            info: '',
            example: 'The Best of C#',
            required: true,
            errorStatus: '',
            errorMessage: ''
        }
    }
}

我希望能够轻松进行更改,例如某个字段的errorMessage,例如与:

this.setDataInFields('title', 'errorMessage', 'Title is required.'); 

执行此操作的语法是什么,例如如果我有此功能:

setDataInFields(idCode, property, value) {
    this.responseData.fields.author.errorMessage = 'changed'; // this works

    //this.responseData[idCode][property] = value; //doesn't work

    //this.responseData.fields = { //doesn't work
    //  [property]: value
    //};

    //this.responseData.fields[idCode][property]['errorMessage'] = value; // doesn't work
}

2 个答案:

答案 0 :(得分:4)

 this.responseData[idCode][property] = value; //doesn't work

您快到了。您忘记在fields键内输入了:

this.responseData.fields[idCode][property] = value

答案 1 :(得分:0)

使用lodash访问深层对象始终是一个好选择,因为如果未定义某些内容可能会引发错误

let field = `fields.` + idCode + '.' + property
_.set(this.responseData, field, value)