Please help me out with a map/reduce. The idea is ...
# suitescript
e
Please help me out with a map/reduce. The idea is to create a Sales Order with multiple items for each customer. In the
getInputData
I got a search result with several columns: CustomerID, ItemID, Quantity, Price, etc. Customer 1, Item 1, Quantity 3, Price 9.99 Customer 1, Item 2, Quantity 2, Price 10.99 Customer 2, Item 1, Quantity 3, Price 5.99 In the
Map
stage I need to group by CustomerID, in order to create the SO in the
Reduce
stage. How do I pass the grouped values from
Map
to
Reduce
?
n
youll use the customerID as the key and the item data as the values You just write back to the mapContext object like this
Copy code
mapContext.write({key: customerId, value: itemDataObj})
That will give you a reduce context that looks like this
Copy code
reduceContext = {values: customerId, values: [{itemData1}, {itemData2}]}
So your key in reduceContext will be the customerId, and values will be an array of the item objects you wrote into the value of mapContext
🙌 1
Copy code
getInputDate(inputContext) {
return search.load({id: searchId})
}

map(mapContext) {
const key = mapContext.key;
const value = JSON.parse(mapContext.value);

const customerId = //do whatever you need to get the customer id
const itemData = {} // populate this object with your item data

// utilizes the native map/reduce functionality to group by customer id
mapContext.write({key: customerId, value: itemData}); 
}

reduce(reduceContext) {
const customerId = reduceContext.key;
const arrayOfItemDataObjects = reduceContext.values.map(JSON.parse);

// ... do whatever processing on the data you need
}
🙌 1
e
slight adjustment;
reduceContext.values
is an Array, not a JSON string, so
Copy code
const arrayOfItemDataObjects = reduceContext.values.map(JSON.parse);
🙏 1
otherwise 👍 👍
n
good catch. I was going from memory. And memory failed me lol. Ill adjust my code
e
I only caught it because I've made that mistake about 50,000 times
💯 3
e
Thank you all!!! It works perfectly 😄
apartyblob 1