3 回答
TA贡献1808条经验 获得超4个赞
只需添加一个检查属性是否存在并分配零。稍后将值添加到它。
var depts = ['A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A'],
cnts = [3, 7, 15, 2, 9, 5, 12, 4, 8],
obj = {};
for (var i = 0; i < depts.length; i++) {
if (!obj[depts[i]]) obj[depts[i]] = 0; // use an initial value
obj[depts[i]] += cnts[i]; // add value
}
console.log(obj);
TA贡献1795条经验 获得超7个赞
const depts = [ 'A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A' ];
const cnts = [ 3, 7, 15, 2, 9, 5, 12, 4, 8 ];
let obj = {};
// loop over the first array, if not already in obj, put a zero before adding
depts.forEach((dept,i) => obj[dept] = (obj[dept] || 0) + cnts[i])
console.log(obj);
TA贡献1893条经验 获得超10个赞
var depts = [ 'A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A' ];
var cnts = [ 3, 7, 15, 2, 9, 5, 12, 4, 8 ];
const lkp = depts.reduce((lkp, cur, i) => {
return {
...lkp,
[cur]: ~~lkp[cur] + cnts[i]
}
}, {})
console.log (lkp)
添加回答
举报