cancel
Showing results for 
Search instead for 
Did you mean: 

Create Array from Flattened Docs

alex_panganiban
Contributor

I could really use some help. I have flattened documents and for each distinct product-id value, I wish to create an array list of the variants that belong in the product-id’s family. My desired results should look something like this, but I’m not sure how to get there.

{

"masterproducts": [

{

"product-id": "1",

"variants": [

{

"variant": "988221"

},

{

"variant": "988331"

}]

},

{

"product-id": "1001",

"variants": [

{

"variant": "013356"

},

{

"variant": "933542"

},

{

"variant": "952005"

}]

},

{

"product-id": "1003",

"variants": [

{

"variant": "777100"

}]

}

]

}

 

Here's what I have so far.

 

My pipeline:

image001

Output data from the sort snap. Sorting by product-id, variant.

image

What my GroupBy snap looks like:

image003

13 REPLIES 13

alex_panganiban
Contributor

Hi, I finally got it! Played around more with my expression and finally got what I needed. Sharing my solution:

{ “@product-id” : jsonPath($, “$group[0][‘@product-id’]”), “variations” : { “variants” : $group.reduce((accum, curval) => accum.concat([curval[‘variants’]]), ) } }

Just a couple of notes… The jsonPath() call used in the first part shouldn’t be necessary, you can access the field using a plain expression, like so:

$groupBy['@product-id']

The jsonPath() function would actually be more useful for the second part since you can use a wildcard in the path to traverse the array and extract all values for a given field. So, instead of the reduce() call, you should be able to just do:

jsonPath($, "$group[*].variant")

alex_panganiban
Contributor

okay, i’ll try that out.

alex_panganiban
Contributor

Thought I’d let you know how I was able to remove duplicate entries from my array. I basically was using this reduce method to create my array in a mapper expression.

$product.reduce((accum, curval) => accum.concat([curval[‘variation-attribute-value’][0]]), )

To remove any duplicate entries while the array was being built, I added a filter method to it, like so:

$product.reduce((accum, curval) => accum.concat([curval[‘variation-attribute-value’][0]]), ).filter((item, pos, a) => a.indexOf(item) == pos)

I pretty much just copy/pasted this filter method from the Snaplogic help documentation.

Thanks everyone for your help. I really appreciate all the support.