我想根据动态生成的另一个对象的属性计算对象属性的值的总和。此新对象基于用户交互生成。例如,我有一个具有以下属性的对象:
0 to 100:
<input type="range" min="0" max="1" step="any" step="any"
oninput="sliderOutput(this.value, 0, 100)"
onchange="sliderOutput(this.value, 0, 100)" />
<br />
100 to 0:
<input type="range" min="0" max="1" step="any" step="any"
oninput="sliderOutput(this.value, 100, 0)"
onchange="sliderOutput(this.value, 100, 0)" />
<br />
<br />
Value: <span id="test"></span>
用户选择的对象是:
var valueStore = [
{ item1Price: 4.5,
item2price: 6.5,
item3price: 6.9,
itemCategory: 'inventory'
},
{ item1Price: 4.5,
item2price: 6.5,
itemCategory:'common'
}
];
我想要var selectedStore = [
{
selectedItems: [ item1Price, item2price ],
itemCategory: 'inventory'
},
{
selectedItems: [ item1Price, item2price ],
itemCategory: 'common'
}
];
对象的总价格总和。
答案 0 :(得分:1)
这不是非常优化的解决方案。
var sum = 0;
valueStore.forEach(function (store) {
selectedStore.forEach(function (selected) {
if (selected.itemCategory === store.itemCategory) {
var keys = Object.keys(store);
selected.selectedItems.forEach(function (item) {
if (keys.indexOf(item) > -1) sum += store[item];
});
}
});
});
console.log(sum);
编辑:同样在selectedStore中,您的selectedItems需要是字符串值selectedItems: ['item1Price', 'item2price']