PricingBlog

Change key for JSON object

  • tomthebigtree-1272978403850584064

    Tom Ireland

    1 year ago

    I'm trying to make my chart component flexible so that it can take an object with any key and then convert that key to one that the component expects. For example, say I have:

    {"Days of week":["Mon","Tue","Wed","Thu","Fri"],"Number of requests":[12,45,36,97,78]}

    I'd like to change it to:

    {"x":["Mon","Tue","Wed","Thu","Fri"],"y":[12,45,36,97,78]}

    I could enforce a schema for the component instead and handle keys as additional attributes (for labels, etc.), but looking to see if I can recreate the object so that the keys can be arbitrary.
  • tomthebigtree-1272979851099242650

    Tom Ireland

    1 year ago

    The enforced schema so far (for a bar chart) is object containing x key with array of values and y key with array of values.
  • andreasmoller-1272982127755133079

    Andreas Møller

    1 year ago

    The simplest solution is probably to make a new object and copy the values
  • tomthebigtree-1272983647720312893

    Tom Ireland

    1 year ago

    Good shout, @Andreas Møller - didn't think of that. I assume then that I'd need to store that "converted" object in a component variable, reference that variable for my component internals instead of the attribute object and then pump the values back via an event so they can be viewed?
  • andreasmoller-1272984375419605094

    Andreas Møller

    1 year ago

    I would probably not use a variable unless you need the user to change it somehow, a formula is probably a better choice
    👍1
  • plusmin-1273156701335584770

    Armand

    1 year ago

    Sorry to break in here, but your reply made me wonder if there is a rule of thumb of when to use a formula and when to use a variable.

    I notice myself using both without really knowing which scenario calls for what.
  • andreasmoller-1273159015890817080

    Andreas Møller

    1 year ago

    Yes I just recorded a video about this it will come out next week 🙂

    The rule of thumb is
    “If the value of a variable can at all times be determined if you know the value of the other data in the component, then it probably should not be a variable
  • plusmin-1273173975094132839

    Armand

    1 year ago

    Ah great! Thanks 🙂