1 回答
TA贡献1780条经验 获得超5个赞
这是一个解决方案,它获取一个组的价格,如果给定或所有组,然后将这些组分配给单个数组。
function getPrices(weight, category) {
function getByGroup(group) {
var index = group[0].indexOf(weight);
return group
.map(a => [0, index].map(i => a[i]))
.filter(a => a[1]);
}
return category in allPrices
? getByGroup(allPrices[category])
: Object.entries(allPrices).reduce((r, [k, group], i) => {
var temp = getByGroup(group),
index;
if (!temp.length) return r;
temp[0][1] += '_' + k.slice(-1);
if (!r) return temp;
index = r[0].push(temp[0][1]) - 1;
temp.forEach(([company, price]) => {
var row = r.find(([c]) => c === company);
if (!row) {
r.push(row = [company]);
}
row[index] = price;
});
r.forEach(a => a[index] = a[index] || '');
return r;
}, undefined);
}
var prices_A = [['company', '100g', '200g', '300g'], ['business_a', '40€', '50€', ''], ['business_b', '50€', '61€', '42€'], ['business_c', '66€', '', '31€']],
prices_B = [['company', '100g', '200g', '300g'], ['business_b', '40€', '50€', ''], ['business_d', '50€', '61€', '42€'], ['business_e', '66€', '', '31€']],
prices_C = [['company', '100g', '200g', '300g'], ['business_e', '40€', '50€', ''], ['business_b', '66€', '', '31€']],
allPrices = { prices_A, prices_B, prices_C };
console.log(getPrices('200g', 'prices_C'));
console.log(getPrices('100g', 'prices_all'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报