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

Copy a data multiple times in the same array with iteration

Tanmay_Sarkar
New Contributor III

Hello All,

I stumbled upon a requirement this morning and would like some help/suggestions to work ahead on the solution. I am looking for a way to copy an object inside an array for 36 times while incrementing a specific key inside the object which is a date field.

Example Input:
[

{

    "valueName": "ABC",

    "date": "01/01/2021",

    "someKey": "someValue"

},

{

    "valueName": "XYZ",

    "date": "05/01/2021",

    "someKey": "someValue"

}

]

Example Output:

[

{

    "valueName": "ABC",

    "date": "01/01/2021",

    "someKey": "someValue"

},

{

    "valueName": "ABC",

    "date": "02/01/2021",

    "someKey": "someValue"

},

.

.

.

**Copied 36 times with only the month part getting incremented for 36 times** 

{

    "valueName": "XYZ",

    "date": "05/01/2021",

    "someKey": "someValue"

},

{

    "valueName": "XYZ",

    "date": "06/01/2021",

    "someKey": "someValue"

}

.

.

.

**Copied 36 times with only the month part getting incremented for 36 times**  

]

Only the date key will be incremented each time the object is copied, date key is following a date format of โ€œMM/dd/yyyyโ€ and only MM has to be incremented.

Please advise how this can be achieved using SnapLogic.

1 ACCEPTED SOLUTION

bojanvelevski
Valued Contributor

Hello @Tanmay_Sarkar,

You can use the following expression :

sl.range(36).map(x=>$.mapValues((value,key) => key == โ€˜dateโ€™ ? Date.parse(value).plusDays(x).toLocaleDateString({โ€œformatโ€:โ€œMM/dd/yyyyโ€}) : value))

What it does is the following, the sl.range() function will produce an array of numbers from 0 to 35. On every (x) member of the array, itโ€™s mapping the incoming document, where if the โ€œkeyโ€ is โ€œdateโ€ , increment the date for (x) days, else map the field with no changes.

Best regards,

Bojan Velevski

View solution in original post

2 REPLIES 2

bojanvelevski
Valued Contributor

Hello @Tanmay_Sarkar,

You can use the following expression :

sl.range(36).map(x=>$.mapValues((value,key) => key == โ€˜dateโ€™ ? Date.parse(value).plusDays(x).toLocaleDateString({โ€œformatโ€:โ€œMM/dd/yyyyโ€}) : value))

What it does is the following, the sl.range() function will produce an array of numbers from 0 to 35. On every (x) member of the array, itโ€™s mapping the incoming document, where if the โ€œkeyโ€ is โ€œdateโ€ , increment the date for (x) days, else map the field with no changes.

Best regards,

Bojan Velevski

Hello @bojanvelevski

Hope youโ€™re doing good. This worked. Youโ€™re a savior. I scratched my head all day thinking about this. It never occurred to me that sl.range() could be used like this.

Thanks a lot.

Regards,
Tanmay Sarkar