I have an empty javascript object, and I want to do something like this:
this.conflictDetails[this.instanceId][this.modelName][this.entityId] = { solved: true };
The problem is that for the modelName I get Cannot read properties of undefined. I think it is because the empty object this.conflictDetails does not have the property that I m looking for, I wonder how I could write this to work and to be as clear as possible?
The result should look like:
{
'someInstanceId': {
'someModelName': {
'some entityId': {
solved: true;
}
}
}
}
With mu; time instance ids, that hold multiple model names, that have multiple entity Ids
check this the '?' operator
let obj = {
'someInstanceId': {
'someModelName': {
'someEntityId': {
solved: true
}
}
}
};
let value1 = obj.someInstanceId?.someModelName?.someEntityId;
console.log(value1);
// or
value1 = obj["someInstanceId"] ?? {};
value1 = value1["someModelName"] ?? {};
value1 = value1["someEntityId"];
console.log(value1);
let value2 = obj.someInstanceId?.someMissModelName?.someEntityId;
console.log(value2);
You can use interfaces to define the model of the object, or you can check if every nested object is not null nor undefined.
I would prefer the first option if I use typescript. If not, then i would stick to the not null/undefined option
First we create a model:
export interface CustomObject {
[instanceId: string]: {
[modelName: string]: {
[entityId: string]: {
solved: boolean;
};
};
};
}
Now that we have a model we can fill an object with data:
We define the object in the .ts file of your component
public dataObjects: CustomObject = {
instance1: {
basicModel: {
Entity1: {
solved: false,
},
},
}
};
Now you can have for example a function to change the solved status, I assume that there are several instanceIds, modelNames and entityIds.
public resolveObject(
instanceId: string,
modelName: string,
entity: string,
solved: boolean
) {
this.dataObjects[instanceId][modelName][entity].solved = solved;
}
Now you can call the method with the object details:
this.resolveObject('instance1', 'basicModel', 'Entity1', true);
After this line is executed the solved will changer from false to true.
I've created a StackBlitz to show you: https://stackblitz.com/edit/angular-ivy-ibfohk