cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Mapping the columns matching from the Array

spinaka
New Contributor III

Hello SnapLogic Experts,

I require your help in mapping expression to map the keys(columns).

I need to change the column names in the incoming data according to the mapping list that I have and load it into the database.

Iโ€™m trying to achieve it using mapKeys() but missing something. I really need someoneโ€™s advice to make it. I would be grateful if anyone can solve it. ๐Ÿ™‚

Input data:
[
{
โ€œIDโ€:1,
โ€œNAMEโ€:โ€œtestuserโ€
}
]

Column mapping data from parameter:
[
{
โ€œsrc_col_nameโ€: โ€œIDโ€,
โ€œtgt_col_nameโ€: โ€œsys_idโ€
},
{
โ€œsrc_col_nameโ€: โ€œNAMEโ€,
โ€œtgt_col_nameโ€: โ€œuser_nameโ€
}
]

Expected output:
{
โ€œsys_idโ€:1,
โ€œuser_nameโ€:โ€œtestuserโ€
}

Thank you.

3 REPLIES 3

viktor_n
Contributor II

Hi @spinaka,

I do not understand the โ€œColumn mapping data from parameterโ€. You are sending this array as parameter in the pipeline or something ?

Here is a solution that might help you, if itโ€™s not correct just answer me question above.

My sample data for the expression:

[
  {
  "ID":1,
  "NAME":"testuser",
  "Mapping": [
      {
      "src_col_name": "ID",
      "tgt_col_name": "sys_id"
      },
      {
      "src_col_name": "NAME",
      "tgt_col_name": "user_name"
      }
    ]
  }
]

Expression:
$.mapKeys((value, key) => $Mapping.findIndex(el => el.src_col_name == key) >= 0 ? $Mapping.find(element => element.src_col_name == key).tgt_col_name : key)

Output:

[
  {
    "sys_id": 1,
    "user_name": "testuser"
  }
]

Regards.
Viktor

spinaka
New Contributor III

Amazing @viktor_n. I made a little change and your trick worked perfectly. You deserve an award ๐Ÿ™‚

I will be using it in my original pipeline to see the same result. Would mind clarifying the โ€œfindIndex()โ€ used here?

I transformed the column mapping accordingly. Not an issue.

findIndex() function is used for searching the index of a particular element in Array. If match is not found, -1 is returned.

Syntax: { Array }.findIndex(((element, index, array) => { condition })
Accepts a callback function that returns 3 parameters.

  • First parameter is the value of each element
  • Second is the index
  • Third is the original array.

The returned index is the index of the first element that returns true.

$Mapping.findIndex(el => el.src_col_name == key)

Here inside the expression I check if the โ€˜Mappingโ€™ array has โ€˜src_col_nameโ€™ with a value same as the field from the root($), and if it finds a match it will return the index of that particular element, otherwise it will be -1.

Hope this will help you