Provide a meaningful key name when adding to the end of an existing array

Options

Hi Xano community!

I have hopefully a simple question. See below image. Currently, I add a variable to the end of an existing array but when it's added the key name is 0. Is there a way to give the key name a proper name so that I can easily reference it on my front end application?

Thank you,

Tim

Tagged:

Best Answers

  • Ray Deck
    Ray Deck Trusted Xano Expert ✭✭✭
    Answer ✓
    Options

    Xano's PHP heritage is showing here. It thinks in terms of "associative arrays" which are kind of a blend of what we might otherwise call objects and arrays in a JSON or javascript context. As a result, you can do array functions on what shoudl be objects, leading to this kind of weird result.

    The solution: instead of using "add to end of array", use the update variable call to update the "order.running_total_price" variable to the new value of the current "running_total_price". This is a semantic trick - by referencing the path you want to add, update variable will attach that member, "updating" order, but "adding" the key you are looking for.

    so:

    update variable | variable: "var:order.runring_total_price" value: "var:running_total_price"

  • Tim McIntosh
    Tim McIntosh Member
    Answer ✓
    Options

    Hi @Pawel Magdanski & @Ray Deck

    Thanks for helping me out, appreciate it. I have resolve this on my end but let me know if you think I will encounter problems. In order to provide a key name to the variables, I added the existing variables to a new object variable where I was able to set a path name & the variable as the value. Once I had successfully created my object, I then used the array merge to add to add to the order JSON.
    Ray I really like your suggestion and will look to add it into other solutions or this solution if I start to find defects or bugs. Thanks again. :)

Answers

  • Pawel Magdanski
    Pawel Magdanski Member ✭✭✭
    Options

    Hi,

    Is your array an array of objects? What I see on your screenshot is an object not an array. If yes then where exactly do you want to add this price, inside those objects?

    Can you provide some more context?