[英]How can I edit a specific value deep in a JavaScript object?
我在節點中有以下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
}
this.responseData[idCode][property] = value; //doesn't work
你快到了。 您忘記在fields
鍵中輸入:
this.responseData.fields[idCode][property] = value
使用lodash
訪問深層對象始終是一個不錯的選擇,因為如果未定義某些內容可能會引發錯誤
let field = `fields.` + idCode + '.' + property
_.set(this.responseData, field, value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.