user7665853
user7665853

Reputation: 197

How best can I find the key of a specific value in a nested situation?

In a Lua table, how best can I find the key of a specific value in a nested situation (following table, originating from JSON)?

[{"Code": "AF", "Name": "Afghanistan"},
{"Code": "AL", "Name": "Albania"},
...
]

For example, I can use table[2]["Name"] to fetch "Albania", but how can I get [2], only by specifying "Albania"?

Upvotes: 2

Views: 373

Answers (2)

user7665853
user7665853

Reputation: 197

for i,v in ipairs(table) do
    if string.match(v.Name, countryName) then
        print(i)
    end
end

srting.match is used instead of v.Name == "Albania", as Ive realised there is a possibility in other cases where country names are present, but may not be exactly the same.

Upvotes: 0

ratchet freak
ratchet freak

Reputation: 48196

Loop over the array and test each value:

for i,v in ipairs(table) do
    if v.Name == "Albania" then
        return v.Code
    end
end

You can also put the values as key-pair in a new table once so you can query directly:

local codeFromName={}
for i,v in ipairs(table) do
    codeFromName[v.Name]=v.Code
end

Upvotes: 2

Related Questions