Сначала сохраните сопоставленный массив в переменной, чтобы вы могли проверить length
для определения необходимой цены:
private getSelectedOptions(options) {
const selectedItems = (options || []).filter(x => x.selected);
const price = selectedItems.length >= 6
? 1
: selectedItems.length >= 3
? 1.5
: 2;
return selectedItems.map(
option => ({ name: option.name, value: option.value ? price : 0 })
);
}
const getSelectedOptions = (options) => {
const selectedItems = (options || []).filter(x => x.selected);
const price = selectedItems.length >= 6
? 1
: selectedItems.length >= 3
? 1.5
: 2;
return selectedItems.map(
option => ({ name: option.name, value: option.value ? price : 0 })
);
};
const options = [
{
"name": "Red Pepper",
"selected": true,
"value": 2.00
},
{
"name": "Garlic",
"selected": true,
"value": 2.00
},
{
"name": "Cheese blend",
"selected": true,
"value": 2.00
},
{
"name": "pineapple",
"selected": false,
"value": 2.00
},
{
"name": "bacon",
"selected": false,
"value": 2.00
},
{
"name": "green pepper",
"selected": true,
}
];
console.log(getSelectedOptions(options));
Если параметры могут иметь разные значения, определите коэффициент для их умножения, например 1
или 0.75
или 5
:
const getSelectedOptions = (options) => {
const selectedItems = (options || []).filter(x => x.selected);
const factor = selectedItems.length >= 6
? 0.5
: selectedItems.length >= 3
? 0.75
: 1;
return selectedItems.map(
option => ({ name: option.name, value: option.value * factor })
);
};
const options = [
{
"name": "Red Pepper",
"selected": true,
"value": 5.00
},
{
"name": "Garlic",
"selected": true,
"value": 2.00
},
{
"name": "Cheese blend",
"selected": true,
"value": 2.00
},
{
"name": "pineapple",
"selected": false,
"value": 2.00
},
{
"name": "bacon",
"selected": false,
"value": 2.00
},
{
"name": "green pepper",
"selected": true,
}
];
console.log(getSelectedOptions(options));