Not sure, how should I explain this issue but probably my code snippet can explain this, I have a JS object which I've defined like below:
// This is my current Implementation of code
Class OptionCls {
Constructor(){
this.dataObj = {
name: '',
selectedValue: '',
options: [],
}
}
setOptions(optionArray){
this.dataObj.options = this.prepareOptions(optionArray);
}
prepareOptions(options){
for(let obj of options){
obj.label = obj.label ? obj.label : '';
obj.value = obj.value ? obj.value : '';
// automated properties for dropdown options
Object.defineProperty(obj, '_id', {
value: uniqueId()
});
}
return options;
}
// class end
}
I call setOptions()
method and pass my array of object to set the dataObj.options
.
Now I would like to calculate or define a getter accessor property in the dataObj.options
named as selected
which should automatically read the parent property dataObj.selectedValue
and based on that it should return the value, something like:
prepareOptions(options){
for(let obj of options){
obj.label = obj.label ? obj.label : '';
obj.value = obj.value ? obj.value : '';
// automated properties for dropdown options
Object.defineProperty(obj, '_id', {
value: uniqueId()
});
Object.defineProperty(obj, 'selected', {
get(){
return this.dataObj.selectedValue.split(',').includes(this.value); // Now over here `this` will be refer to local this scope not the parent object
}
});
}
return options;
}
At the end, output of dataObj
should be look like this:
{
name: '',
selectedValue: 'us,uk',
options: [
{
_id: "13",
label: "United States",
value: "us",
selected: true
},
{
_id: "11",
label: "Australia",
value: "au",
selected: false
},
{
_id: "10",
label: "United Kingdom",
value: "uk",
selected: true
}
]
}
How can I achieve this, so far I tried but not able to reference this selectedValue
in the nested object with this
reference