单击按钮后,fruitData 数组中的数据将添加到另一个名为“history”的数组中。我希望每当属性“kultivar”、“blokNommer”和“year”与从fruitData 添加的对象匹配时,历史记录中的属性“bins”就会更新。(如果有匹配,则 bins 属性内的数字需要相加)
例如这个:
[
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"}
]
应等于此(垃圾箱:40):
[
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "40", year: "2020"}
]
我的代码:
let fruitData = [{
datum: "2020-04-08",
kultivar: "bc",
ha: "5",
blokNommer: "1",
bins: "20",
year: "2020"
},
{
datum: "2020-09-18",
kultivar: "wb",
ha: "5",
blokNommer: "1",
bins: "5",
year: "2020"
},
{
datum: "2020-03-09",
kultivar: "bc",
ha: "5",
blokNommer: "1",
bins: "20",
year: "2020"
},
{
datum: "2020-04-08",
kultivar: "bc",
ha: "5",
blokNommer: "1",
bins: "20",
year: "2020"
}
]
historyButton.addEventListener('click', () => {
addToHistory(fruitData)
})
function addToHistory(elements) {
for (let elem in elements) {
history = [...history, elements[elem]];
}
sortHistory()
}
function sortHistory() {
let newHistory = [];
history.forEach(function(item, index) {
if (newHistory.length === 0) {
newHistory.push(item)
} else {
newHistory.forEach(function(itm, idx) {
if (item.year === itm.year && item.kultivar === itm.kultivar && item.blokNommer ===
itm.blokNommer) {
item.bins = item.bins + itm.bins
} else {
newHistory.push(item)
}
})
}
})
console.log(newHistory)
}
这没有给出我正在寻找的输出。也尝试过减少方法但没有运气。将不胜感激任何帮助!
海绵宝宝撒
噜噜哒
繁星coding
相关分类