[Solved] [Issue #408] How do I change a value in an array?

Solution:

You can achieve the goal of setting one element in an array by using the javascript array api function splice, and replace the whole array in kantu. And then assign it to the array again:

arr = storedVars['names'], arr.splice(${num}, 1, "Pink Elephant"), arr

If num = 2, this changes the 2nd element of the array from “dog” to “pink elephant”.

array1

Complete test macro:

{
  "Name": "replace element in how array",
  "CreationDate": "2018-12-9",
  "Commands": [
    {
      "Command": "store",
      "Target": "fast",
      "Value": "!replayspeed"
    },
    {
      "Command": "open",
      "Target": "https://a9t9.com/kantu/demo/storeeval",
      "Value": ""
    },
    {
      "Command": "storeEval",
      "Target": "new Array ('cat','dog','fish','dog','??','frog','?','dog','??','horse','??elephant')",
      "Value": "names"
    },
    {
      "Command": "store",
      "Target": "2",
      "Value": "num"
    },
    {
      "Command": "comment",
      "Target": "change value 2 of the array from \"dog\" to \"pink elephant\"",
      "Value": "green"
    },
    {
      "Command": "storeEval",
      "Target": "arr = storedVars['names'],  arr.splice(${num}, 1, \"Pink Elephant\"), arr",
      "Value": "names"
    },
    {
      "Command": "storeEval",
      "Target": "storedVars['names'][${num}] ",
      "Value": "newname"
    },
    {
      "Command": "echo",
      "Target": "The ${num}nd element of the array is now ${newname}",
      "Value": "pink"
    }
  ]
}
1 Like