Reputation: 2351
Given the following data structure, where product_variations can have other product_variations as children, I am looking for a terse algorithm that will extract all of the 'product_variations' that are children to one 'product_variation', but all I have is the SKU
product_variations: [
{
product_variation_id: "",
variation_name: variation_name,
variation_item_name: "test",
sku: "SKU000",
price: price,
stock: stock,
topLevel: true,
child_variations: [{sku: "SKU001"}]
},
]
I was thinking reduce could be useful for this, as I can iterate through each of the child_variations, and then use a find function to grab the relevant SKU from the product_variations array and push that to the accumulator. I am trying to get something like this to work:
const extractChildrenVariations = (variationItem, variations) => {
return variationItem.child_variations.reduce( (arr, {sku: s}) => arr.push(
variations.find( v => v.sku == s)
), [])
}
I think this could be the problem; sometimes there aren't any child_variations to begin with, ie. child_variations: [{}]
Anyone see what I might be doing wrong? I am confident that if the SKU is in the child_variations array that variations.find with that SKU will turn something up (since it definitely exists)
Upvotes: 1
Views: 49
Reputation: 13356
It can be more readable with array.filter
:
const extractChildrenVariations = (variationItem, variations) => {
return variations.filter(v => variationItem.child_variations.find(cv => cv.sku === v.sku));
}
Upvotes: 1