Reputation: 1426
I have a class definition…
class anObj {
"ID" : string;
dialog: {[id : number]:{hide: boolean;}} = {
0 : {"hide": false},
14 : {"hide": false}
}
}
class manyObjects {
myGroup: anObj [] = [];
}
...
public stuff = manyObjects;
This totally works just the way I'd like for it to...I can use the id value as a direct key...
var x:number = 1 //used for a different tier of logic
stuff.myGroup[x].dialog[14].hide!=true
Here's where I'm stuck... I'd like to add more dialogs to the group. I get all the way our to...
stuff.myGroup[x].dialog
and can't figure out how to add something like with a push...
.push(7 : {"hide": true})
for example, I can type this line and the IDE says it's ok...
stuff.myGroup[x].dialog[[id=7].push({"hide": false})];
however, when I check, the element does not get added to the array...
Upvotes: 1
Views: 2795
Reputation: 2454
What I could gather from your code is that you're trying to add a new dialog to the object contained in the "dialog" property of anObj, which is not an array. It's an object with an expected structure in typescript: every property of that object should be a number, and the value of every property should be of type {hide: boolean;}.
From there, it's quite easy, you add a new property (or overwrite an existing one) as you do for any JS object:
stuff.myGroup[x].dialog[7] = {hide: false};
Again, stuff.myGroup[x].dialog is an object, not an array, the array is stuff.myGroup. If you want to add another "group" to myGroup then you'd do something like:
stuff.myGroup.push(new anObj());
EDIT
Example that ignores the noise created by extra objects like stuff and my group, but demonstrates adding a new key-value pair:
class anObj {
"ID" : string;
dialog: {[id : number]:{hide: boolean;}} = {
0 : {"hide": false},
14 : {"hide": false}
}
}
class manyObjects {
myGroup: anObj [] = [];
}
var obj = new anObj();
obj.dialog[7] = { hide: true };
console.log(obj);
You can try that in typescript playground -> https://www.typescriptlang.org/play/?ssl=14&ssc=18&pln=1&pc=1#code/MYGwhgzhAEYHYHkBGAraBvaAoa0BEAkgCJ7QBc0EALgE4CWcA5gNw7QAmdYIA9oxegDadduWhwArgFskAUxoBdMugAWI2RSQ8eIWfGYBfA9AC8GNrgAMY9HjXtZeCgDNuEWQYA0F6AEYALDZ26k7QriDuBmzGuNhRoJAwUvAAnsgossBUMOhsUikA4jQ8EgAOFPDp0IIKptUKrFFYAG5gNNA8qHVwsgDusIioABQAlKydKAB0nNx8ggDstWaY9hrQtBKy0AaswDxwEDqyk7yMQxNjQA
Update 2
To return the enumerable keys of an object, you can use the Object.keys method. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
console.log(Object.Keys(obj));
Upvotes: 1