How do you change a dictionary's key name in insert.table?

Hello, I’m familiarizing myself with Roblox studio and I’ve hit a wall and don’t know what to do. I’ve looked for a long and haven’t found a solution, or perhaps I’m just not looking hard enough.

local Table = {
    ["Key"] = {
        ["Name"] = "Name",
        ["Description"] = "Description"
    }
}

table.insert(Table, "test")

This is the result, and I want to change the “[1]” to something else or whatever I want it to be.

{
    -- This the new table inserted from table.insert()
    [1] = "test",

     ["Key"] =  ?  {
         ["Description"] = "Description",
         ["Name"] = "Name"
      }
 }
1 Like

To set the key of a table to do something you can:

Table[“Key”] = RANDOM_VALUE

If you want to change “[1]” to something else while retaining its value, you can:

Table[NEW_KEY] = Table[1] — swaps keys
Table[1] = nil — removes old key
5 Likes

I’ve got one more question how do you rename them with their name value on loop?
This is the array that will be inserted to

local tests = {
	Apple = {
		Name = "Apple",
		Description = "Amazing apple yeah"
	}
}

This is the array that we need to insert to tests

local array1 = {
	["banana"] = {
		["Name"] = "banana",
		["Description"] = "yellow"
	},
	["potato"] = {
		["Name"] = "potato",
		["Description"] = "chips"
	}
}

So what I’m trying to do is basically loop through the array1 and insert each key and values and how would you go on renaming them with the Name value?

for i, v in pairs(array1) do
	table.insert(tests, v)
end

You shouldn’t be using table.insert because “tests” is a dictionary and table.insert is only really useful for arrays since it appends a value at the last numerical index (unless you specify an index to insert at).

You can just set the value of the key at the current iteration of the for loop to the table containing “Name” and “Description” directly, e.g.:

tests[i] = v

It’s also nice to give your variables meaningful names so you don’t get lost in your code later on

for foodItem, foodData in pairs(array1) do
    tests[foodItem] = foodData
end

The “tests” dictionary should now look like this:

{
	["Apple"] = {
		["Description"] = "Amazing apple yeah",
		["Name"] = "Apple"
	},
	["banana"] = {
		["Description"] = "yellow",
		["Name"] = "banana"
	},
	["potato"] = {
		["Description"] = "chips",
		["Name"] = "potato"
	}
}
4 Likes

I see thank you, I thought the tables, dictionaries, and arrays are the same.