# Painless script that takes values from nested object and turns it into a field

**URL:** <https://discuss.elastic.co/t/painless-script-that-takes-values-from-nested-object-and-turns-it-into-a-field/271099>\
**Category:** Elasticsearch\
**Created:** [April 23, 2021, 2:03pm UTC](https://discuss.elastic.co/t/painless-script-that-takes-values-from-nested-object-and-turns-it-into-a-field/271099 "2021-04-23T14:03:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sander\_Marx](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/sander_marx/32/80406_2.png) [@Sander\_Marx](https://discuss.elastic.co/u/Sander_Marx)\
**Post date:** [April 23, 2021, 2:03pm UTC](https://discuss.elastic.co/t/painless-script-that-takes-values-from-nested-object-and-turns-it-into-a-field/271099/1 "2021-04-23T14:03:44Z")

</div>

I Have a customFields nested object

```auto
             "customFields" : [
            {
              "description" : "Description",
              "Name" : "Document Author"
            },
            {
              "description" : "This is a description",
              "Name" : "document name"
            }
]

```

I want to transform this into single fields like this:

```auto
    "Document Author" : "Description",
    "Document name" : "This is a description"

```

When i run my painless script in kibana:

```auto
    POST /new_document-20_v4/_update_by_query
{
  "script": {
    "inline": "\n def source_copy = ctx._source;\n def customFields = source_copy.remove('customFields');\n \n for (int i = 0; i < customFields.length; i++) {\n // store the current iteratee\n def current = customFields[i];\n \n // remove AND return the name\n def name = current.remove('Name'); \n def desc = current.remove('descripion'); \n \n // set in the _source\n source_copy[name] = desc;\n }\n \n // replace the original source completely\n ctx._source = source_copy;\n "
,
    "query": {
      "bool": {
        "must": [
          {
            "exists": {
              "field": "customFields.Name"
            }
          }
        ]
      }
    }
  }
}

```

It returns them as single fields, but with a null value.

```auto
"Document Author" : null,
"Document name" : null

```

I a little confused as to why this happens, i am a little new to elasticsearch and painless scripting in general so if anyone can help me out it would be greatly appreciated!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 21, 2021, 2:04pm UTC](https://discuss.elastic.co/t/painless-script-that-takes-values-from-nested-object-and-turns-it-into-a-field/271099/2 "2021-05-21T14:04:22Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
