lualua-tabletarantooltarantool-cartridge

Adding a new field to each array element in .lua


Please tell me, if there are any errors here and how to make the code more clean.

There is a space "company". Inside it's a string "type" and "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.

I need to add a new field:

status = "UPDATED"

inside each object in the "users" array, under a certain condition

"company": {
  "type" : "01",
  "information":
    {
      "job":
        {
          "job_name": "N",
          "job_address": 1670392687114,
          "job_salary": 1234567890123,
          "contacts": 0
        },
      "users":
        [
          {
            "id": 1,
            "name": "Alex",
            "rate": 4,
            "address": "bla bla bla"
          },
          {
            "id": 2,
            "name": "Jenifer",
            "rate": 5,
            "address": "bla bla bla"
          }
        ]
    }
}

My logic is next:

if tuple.type == "01" or tuple.type == "02" or tuple.type == "03" or tuple.type == "04" then
   for _, attr in pairs(users) do
      attr.status = "UPDATED"
   end
end

Is it correct to add a new status="UPDATED" field to each object in the array "users" here? Does this entry exist?

And yet, tell me please, can I somehow make the condition in if more beautiful? For example analog in Java list.contains()


Updated:

The final version after adding new field "status" should look like this (see image) enter image description here


Solution

  • Is it correct to add a new status="UPDATED" field to each object in the array "users" here? Does this entry exist?

    If you want the table to have a status field with value "UPDATED" then attr.status = "UPDATED"is correct.

    This only makes sense if you'll add more non-updated users to that table later though as you're updating the entire list. you could as well just mark the users table object as updated.

    And yet, tell me please, can I somehow make the condition in if more beautiful? For example analog in Java list.contains()

    No but you could write your own function.

    function table.contains(tbl, value)
      for _, v in pairs(tbl) do
        if (v == value) then return true end
      end
      return false
    end
    
    if table.contains({"01", "02", "03", "04"}, tuple.type) then
      for _, attr in pairs(users) do
        attr.status = "UPDATED"
      end
    end
    

    Alternatively you could use a lookup table

    local isUpdateType = {
      ["01"] = true,
      ["02"] = true,
      ["03"] = true,
      ["04"] = true,
    }
    

    and later

    if isUpdateType[tuple.type] then end
    

    How to solve this depends very much on what you consider "beautiful" here.