Search code examples
javascripttraversaljsonata

JSONata get parent element


In a rather complex JSON-object I am trying to get a key with a parent value.

{
    "provinces": [
        {
            "short": "ska",
            "tiletype": "water",
            "provinceOutlinePath": "M255.848,145.321l19.839,0.054l12.677,8.62l6.085,-8.62l-8.62,-29.41l-30.488,13.637l0.507,15.719Z",
            "unionParts": [
                {
                    "id": "main",
                    "unionPartPath": "M255.848,145.321l19.839,0.054l12.677,8.62l6.085,-8.62l-8.62,-29.41l-30.488,13.637l0.507,15.719Z"
                },
 {
                    "id": "main",
                    "unionPartPath": "M255.848,145.321l19.839,0.054l12.677,8.62l6.085,-8.62l-8.62,-29.41l-30.488,13.637l0.507,15.719Z"
                }
            ]
        },
        {
            "short": "nws",
            "tiletype": "water",
            "provinceOutlinePath": "M140.038,0.667l34.86,68.197l-6.338,27.888l12.677,3.169l70.988,-17.747l100.144,-62.115l1.268,-19.392l-213.599,0Z",
            "unionParts": [
                {
                    "id": "main",
                    "unionPartPath": "M140.038,0.667l34.86,68.197l-6.338,27.888l12.677,3.169l70.988,-17.747l100.144,-62.115l1.268,-19.392l-213.599,0Z"
                }
            ]
        }
   ]
}

I want to alter the object to:

[
  { 
    "short": ska,
    "unionPartPath": "<Path>"
  },
  { 
    "short": ska,
    "unionPartPath": "<AnotherPath>"
  },
  { 
    "short": nws,
    "unionPartPath": "<Path>"
  }
]

I already browsed the whole docs and found nothing like a .parent() method.
Maybe the desired result could be achieved with some higher order functions but currently I have no clue how to implement this.


Solution

  • To do this in JSONata, you need the following expression

    provinces.($short := short; unionParts.{
      'short': $short,
      'unionPartPath': unionPartPath
    })
    

    See http://try.jsonata.org/H1goy6AjE