3 回答
TA贡献1809条经验 获得超8个赞
您需要迭代原始数组,并使用检索数组中与 , 匹配的find()现有项目,以便访问和更新它。historykultivarblokNommeryearbins
注意:在示例中将binsby转换为其字符串也很重要,然后将其转换回.Number()string
const arr = [
{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"}
]
const history = [];
arr.forEach(item => {
const found = history.find(({ kultivar, blokNommer, year }) =>
kultivar === item.kultivar && blokNommer === item.blokNommer && year === item.year)
if(found) {
found.bins = (Number(found.bins) + Number(item.bins)).toString();
} else {
history.push(item);
}
});
console.log(history);
TA贡献1784条经验 获得超7个赞
如果您的fruitData数组不是很大,您可以尝试使用迭代元素并搜索indexOf整个数组,将其转换为字符串JSON.stringify
但如果数组很大,则代码不是最佳的
const 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"}]
const sortHistory = (myArray) => Object.keys(myArray).reduce((accum, item) => {
const currItem = JSON.stringify(myArray[item])
const allArr = JSON.stringify(accum)
return (allArr.indexOf(currItem) >= 0) ? accum : accum.concat(myArray[item])
}, [])
console.log(sortHistory(fruitData))
TA贡献1797条经验 获得超4个赞
您的实施的问题是您正在更改itm.bins. Array.forEach 在遍历每个元素时创建每个元素的副本,因此您更改的任何值都itm不会反映在实际数组中。idx因此,如果您想更改实际元素,则会向您提供。
另外,您用于+添加字符串,而不是整数。您需要先将其转换为整数才能获得所需的结果。
最终代码应该是:
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){
newHistory[idx].bins = parseInt(item.bins) + parseInt(itm.bins);
}else{
newHistory.push(item)
}
})
}
})
console.log(newHistory);
history = newHistory;}
- 3 回答
- 0 关注
- 112 浏览
添加回答
举报