I need to find the two nested objects from 'products.accessories' array in 'accessories' array and check their currency to multiply with parity, check their unit to multiply with 'products.properties.length', multiply each with their 'qty' and sum their result.
Any suggestion is much appreciated. Thanks.
var accessories = [{
name: 'Accessory-1',
currency: 'eur',
price: 1,
unit: 'm'
},
{
name: 'Accessory-2',
currency: 'usd',
price: 2,
unit: 'pcs'
}];
var products = [{
name: 'Product',
properties: [{
no: 'Product-1',
length: '2000',
accessories: [{
name: 'Accessory-1',
qty: 1
},
{
name: 'Accessory-2',
qty: 1
}]
}]
}];
// currencies
let eurusd = 1.18
let gbpusd = 1.38
function getPrice(accessory) {
accessory.unit === 'm' ? unitMultiplier = length / 1000 : unitMultiplier = 1
return (
accessory.currency === 'eur' ? (accessory.price * eurusd) :
(accessory.currency === 'gbp' ? (accessory.price * gbpusd) :
accessory.price)
).toFixed(2)
}
function getAcc(property) {
return property.accessories
.map(x => x.qty * getPrice(accessories.find(p => p.name === x.name)) * unitMultiplier)
.reduce((c, p) => c + p)
}
PUG:
each i in products
.....
each j in i.properties
.....
length = j.length
.....
// Accessories: each accessory might be presented several times with different currencies
var accessories = [
{
name: 'Accessory-1',
currency: 'eur',
price: 3,
unit: 'm',
},
{
name: 'Accessory-2',
currency: 'eur',
price: 5,
unit: 'm',
},
{
name: 'Accessory-3',
currency: 'usd',
price: 2,
unit: 'pcs',
},
]
// Products - each product has properties with "accessories" inside
var products = [
{
name: 'Product',
properties:
[
{
no: 'Product-1',
length: '2000',
accessories: [
{
name: 'Accessory-1',
qty: 2
},
{
name: 'Accessory-2',
qty: 2
},
{
name: 'Accessory-3',
qty: 1
},
]
},
]
}
];
//currencies
let eurusd = 1.18;
let gbpusd = 1.38;
//functions
function getPrice(product) {
return (
product.currency === 'eur' ? (product.price * eurusd) :
(product.currency === 'gbp' ? (product.price * gbpusd) :
product.price)).toFixed(2);
}
// The function gets one product as an incoming parameter
// Then gets the list of all accessories for all properties
// Finds the accessory from the global array, calculates right price
// based on accessory currency and multiplies it by accessory quantity
// Then summarises all prices
function getAccessories(product) {
return product.properties
.map(x => ({
accessories: x.accessories.map(b => ({
...b,
length: +x.length
}))
}))
.flatMap(x => x.accessories) // get all accessories
.map(x => x.length * x.qty * getPrice(accessories.find(p => p.name === x.name))) // find the price of accessory from global array
.reduce((c, p) => c + p) // sum prices
;
}
console.log(getAccessories(products[0]));