Q:

Recurse for object if exists in JQ

I have the following structure:
{
    "hits": 
    [
        {
            "_index": "main"
        },
        {
            "_index": "main",
            "accordions": [
                {
                  "id": "1",
                  "accordionBody": "body1",
                  "accordionInnerButtonTexts": [
                    "button11",
                    "button12"
                  ]
                },
                {
                  "id": "2",
                  "accordionBody": "body2",
                  "accordionInnerButtonTexts": [
                    "button21",
                    "button22"
                    ]
                }
              ]
        }
    ]
}

I want to get to this structure:
{
    "index": "main"
}
{
    "index": "main",
    "accordions": 
    [
        {
            "id": "1",
            "accordionBody": "body1",
            "accordionInnerButtonTexts": [
                "button11",
                "button12"
             ]
         },
         {
             "id": "2",
             "accordionBody": "body2",
             "accordionInnerButtonTexts": [
                 "button21",
                 "button22"
             ]
         }
     ]
}

Which means that I always want to include the _index-field as index, and I want to include the whole accordions-list IF IT EXISTS in the object. Here is my attempt:
.hits[] | {index: ._index, accordions: recurse(.accordions[]?)}

It does not produce what I want:
{
  "index": "main",
  "accordions": {
    "_index": "main"
  }
}
{
  "index": "main",
  "accordions": {
    "_index": "main",
    "accordions": [
      {
        "id": "1",
        "accordionBody": "body1",
        "accordionInnerButtonTexts": [
          "button11",
          "button12"
        ]
      },
      {
        "id": "2",
        "accordionBody": "body2",
        "accordionInnerButtonTexts": [
          "button21",
          "button22"
        ]
      }
    ]
  }
}
{
  "index": "main",
  "accordions": {
    "id": "1",
    "accordionBody": "body1",
    "accordionInnerButtonTexts": [
      "button11",
      "button12"
    ]
  }
}
{
  "index": "main",
  "accordions": {
    "id": "2",
    "accordionBody": "body2",
    "accordionInnerButtonTexts": [
      "button21",
      "button22"
    ]
  }
}

It seems to create a list of all different permutations given by mixing the objects. This is not what I want. What is the correct jq command, and what is my mistake?

A:

The problem as stated does not require any recursion.  Using your attempt as a model, one could in fact simply write:
.hits[]
| {index: ._index} 
+ (if has("accordions") then {accordions} else {} end)

Or, with quite different semantics:
.hits[] | {index: ._index} + . | del(._index)

