Godot Version
4.2.1 Stable
Question
Hello, I’m developping a game and for it I need to use a dictionnary. Here’s my issue, I need to find a way to delete an object.
Here’s my dictionnary :
var localDict = {"enigmas" :[
{
"answer": "8",
"fakeAnswer1": "5",
"fakeAnswer2": "3",
"fakeAnswer3": "8",
"question": "question1",
"solution": "solution1"
},
{
"answer": "10",
"fakeAnswer1": "8",
"fakeAnswer2": "4",
"fakeAnswer3": "2",
"question": "question2",
"solution": "solution2"
}
]
}
My goal is to find a way to delete completely the first object ( without doing it manually ) !
Thanks for any kind of help !
Hello,
You can use Dictionary.erase(key)
.
More information is available in the godot documentation for Dictionary.
Regards,
1 Like
It works, thanks !
but like this :
localDict.enigmas[0].erase("question")
localDict.enigmas[0].erase("answer")
localDict.enigmas[0].erase("fakeAnswer1")
localDict.enigmas[0].erase("fakeAnswer2")
localDict.enigmas[0].erase("fakeAnswer3")
localDict.enigmas[0].erase("solution")
The problem is that when everything is erased, there’s still an empty object.
Console print of LocalDict :
{ "enigmas": [{ }, { "answer": "10", "fakeAnswer1": "8", "fakeAnswer2": "4", "fakeAnswer3": "2", "question": "question2", "solution": "solution2" }
Do you have any idea on how to solve this ?
Thanks
Hello,
Deleting all of the elements in a Dictionary does not delete the dictionary itself. In the context of an Array, you can use Array.remove_at(index)
to remove the element in the Array at the specified index. In other contexts, setting the dictionary to null should be sufficient.
If the intention is to remove a dictionary from an array only when the dictionary is empty, this will require you to write some handling code to do so.
func delete_dict_key_or_dict_if_empty(array:Array, index:int, key:String)
array[index].erase(key)
if array[index].is_empty():
array.remove_at(index)
The above was written as example only. Your particular use-case might require different implementation.
Regards,
1 Like