我需要在“附件”数组中从'products.accessories‘数组中找到两个嵌套对象,并检查它们的货币与奇偶乘,检查它们的单位乘以’Products.properties. result‘,用它们的'qty’乘以每个对象,并将它们的结果相加。
任何建议都是非常感谢的。谢谢。
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编辑:谢谢,AlexeyZelenin
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
.....发布于 2021-10-14 18:50:25
// 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]));
https://stackoverflow.com/questions/69574976
复制相似问题