Forum Discussion

Ajay_Chawda's avatar
Ajay_Chawda
Contributor
7 years ago

Adding element to array

Input json :-[
{
“e_no”: “1”,
“email”: “abc@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “B”,
“data”: [
{
“e_no”: “12”,
“email”: “abc4@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “c”
},
{
“e_no”: “13”,
“email”: “abc3@gmail.com”,
“country”: “US”,
“firstname”: “A”,
“last name”: “d”
},
{
“e_no”: “14”,
“email”: “abc2@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “n”
},
{
“e_no”: “15”,
“email”: “abc1@gmail.com”,
“country”: “UK”,
“firstname”: “A”,
“last name”: “f”
}
]
},
{
“e_no”: “4”,
“email”: “a@gmail.com”,
“country”: “India”,
“firstname”: “c”,
“last name”: “D”
},
{
“e_no”: “5”,
“email”: “b@gmail.com”,
“country”: “US”,
“firstname”: “C”,
“last name”: “D”
}
]

Output JSON required :-
[
{
“e_no”: “1”,
“email”: “abc@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “B”,
“data”: [
{
“e_no”: “12”,
“email”: “abc4@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “c”,
“age”:“12”
},
{
“e_no”: “13”,
“email”: “abc3@gmail.com”,
“country”: “US”,
“firstname”: “A”,
“last name”: “d”,
“age”:“13”
},
{
“e_no”: “14”,
“email”: “abc2@gmail.com”,
“country”: “India”,
“firstname”: “A”,
“last name”: “n”,
“age”:“14”
},
{
“e_no”: “15”,
“email”: “abc1@gmail.com”,
“country”: “UK”,
“firstname”: “A”,
“last name”: “f”,
“age”:“15”
}
]
},
{
“e_no”: “4”,
“email”: “a@gmail.com”,
“country”: “India”,
“firstname”: “c”,
“last name”: “D”
},
{
“e_no”: “5”,
“email”: “b@gmail.com”,
“country”: “US”,
“firstname”: “C”,
“last name”: “D”
}
]

wanted to add element in array with values of e_no.

5 Replies

  • Looks like a frustrated emoji on the end of that line 😄

    If I understand you correctly, you want to add a new field called age to each element in your input as well as any field called data in an input document. To do this you can use the map function on the data array to apply a transformation to each element of the array.

    Here’s what it looks like in the expression language:

    $.data.map(e => e.extend({'age': e.e_no}))
    

    This says, for each element of $.data extend it with a new field called age that is just a mapping of e_no. Putting this in the mapper will look like

    Note that this will also append a data field to each element of the array. If it was missing, then the value will be null. You could filter these out downstream if you like.

    • KTsnap's avatar
      KTsnap
      New Contributor III

      What needs to be done if i want to add one more record in this array for example
      {
      “e_no”: “6”,
      “email”: “c@gmail.com”,
      “country”: “US”,
      “firstname”: “C”,
      “last name”: “D”
      }

      • tlikarish's avatar
        tlikarish
        Employee

        The extend method let’s you extend the object with more than one field, so you could do

        $.data.map(e => e.extend({'age': e.e_no, 'email': e.email, 'country': e.country....}))