# Loop through array and create new field values

**URL:** https://discuss.elastic.co/t/loop-through-array-and-create-new-field-values/209826
**Category:** Logstash
**Created:** [November 28, 2019, 10:16am UTC](https://discuss.elastic.co/t/loop-through-array-and-create-new-field-values/209826 "2019-11-28T10:16:34Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![karlm](https://avatars.discourse-cdn.com/v4/letter/k/d2c977/32.png) [@karlm](https://discuss.elastic.co/u/karlm)
#### Post date: [November 28, 2019, 10:16am UTC](https://discuss.elastic.co/t/loop-through-array-and-create-new-field-values/209826/1 "2019-11-28T10:16:34Z")

</div>

I have an xml filter creating two arrays from an xml sql column, there could be any amount of values in the arrays.

```
xml {       
    source => "event_xml"              
    remove_namespaces => true 
    store_xml => false
    xpath => [ "/Data/Name/text()", "Key" ,
               "/Data/Value/text()", "Value" ]
  }

```

I need to loop through each array to make sure its not null and has same count as the 2nd array.

Then create new fields and the values from said arrays. my ruby code below is;

```
ruby {
    code => '
      keys = event.get("Key")
      values = event.get("Value")      
      if keys.length == values.length
        keys.each_index { |i| event.set("keys[i]", values[i]) }
      end
    '
  }

```

ruby exception being received.

`invalid FieldReference: `keys[i]`

Is what i'm trying to do possible or is it ruby syntax off?

thanks

---

<div class="post-metadata">

### Author: ![karlm](https://avatars.discourse-cdn.com/v4/letter/k/d2c977/32.png) [@karlm](https://discuss.elastic.co/u/karlm)
#### Post date: [November 28, 2019, 12:52pm UTC](https://discuss.elastic.co/t/loop-through-array-and-create-new-field-values/209826/2 "2019-11-28T12:52:41Z")

</div>

ruby {  
code =\> '  
keys = event.get("[Key]")  
values = event.get("[Value]")  
if not(keys == nil) && (keys.length == values.length)  
keys.each\_with\_index { |val, i| event.set("#{val}", values[i]) }  
end  
'  
}

---

<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: [December 26, 2019, 12:52pm UTC](https://discuss.elastic.co/t/loop-through-array-and-create-new-field-values/209826/3 "2019-12-26T12:52:55Z")

</div>

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