Add filter to change or replace key names in an object.

Options

The filter should take an object such as {"key1":"value1","key2":"value2", "key3":"value3"} and provide a list of text to replace the key names e.g. ["mykey1","mykey2","mykey3"}

and return: {"mykey1":"myvalue1","key2":"myvalue2", "key3":"value3"}.

WHY? At times, one needs to provide more descriptive keys to the frontend (a major/regular demand from frontend developers), that are not necessarily the same on the table columns. So, it would be great, if after all the manipulation on the function stack, one can change the key names as one wishes without much hassles.

Comments

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

    It's relatively straightforward to do this, looping over your resultset and running some "update variable" calls on it. You target the variable (var) item.mykey1, and set it to the value (var) item.key1. This will expand the set.

    The alternative if you want key1 to no longer be present, is more of a map pattern:
    1) create an accumulator variable - blank array
    2) set up the for-each loop
    3) create a variable - blank object
    4) in a series uof update variables, set up "newobject.mykey" to be "item.key" etc.
    5) add the variable to the end of the accumulator array.
    6) after the loop, return the accumulator array.

    This is a little bit of ceremony but not a whole lot. The pattern is in keeping with Xano exposing primitives to you to set up manipulation tasks as you see fit, rather than larger legos you assemble.

  • Alimama
    Alimama Member
    edited June 2023
    Options

    Hi @Ray Deck

    Many thanks for your response and for your guidance.

    I have worked on such a solution (below function stack) but the object only returns entries where values are not null, I would like to return entries with null values too. That is where the key looped is ["a","b","c"] and the values is [1,2,null], the object returned from create_object is {"a":1, "b":2}, the c:null is not returned. Could you help with an idea on how to solve this? Thanks a mil!

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

    From here I can't really tell how you are working the loop, but what I would do is make an "output" variable that is an object, and then update that object with a for (not a for-each) loop. That loop would be based on the count of the object_keys. Then "get" the key and the value at that index. Then "update variable" to update the object at that path at that key. I've tested - this technique works.

    I have tested it because at State Change we as a community focus on the hardest 5% of problems in low-code projects in our office hours and forums. These problems often relate to data wrangling, as yours does today. It's all workable with a bit of patience, and sometimes a little help!