将两个 javascipt 数组组合成一个对象并将值相加

我想组合以下两个相同大小的数组:


var depts = [ 'A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A' ];

var cnts  = [  3,   7,  15,   2,   9,   5,   12,  4,   8  ];

在这样的对象中,注意 cnts 是每个部门的总数:


{A: 15, D: 19, M: 15, G: 2, B: 5}

通常我在网站集成之前执行数据操作,但是我想开始在 JavaScript 中执行它。一些代码大致模仿了我正在尝试做的事情。


var obj = {};

for(var i = 0; i < depts.length; i++)

{

    console.log(depts[i], cnts[i]);

    obj[depts[i]] = cnts[i]; // <-  don't know how to increment assignment 

}

console.log(obj);

此代码创建一个对象,但不会按部门对 cnts 求和:


{A: 8, D: 12, M: 15, G: 2, B: 5}


达令说
浏览 99回答 3
3回答

炎炎设计

只需添加一个检查属性是否存在并分配零。稍后将值添加到它。var depts = ['A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A'],&nbsp; &nbsp; cnts = [3, 7, 15, 2, 9, 5, 12, 4, 8],&nbsp; &nbsp; obj = {};for (var i = 0; i < depts.length; i++) {&nbsp; &nbsp; if (!obj[depts[i]]) obj[depts[i]] = 0; // use an initial value&nbsp; &nbsp; obj[depts[i]] += cnts[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // add value}console.log(obj);

一只萌萌小番薯

const depts = [ 'A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A' ];const cnts&nbsp; = [&nbsp; 3,&nbsp; &nbsp;7,&nbsp; 15,&nbsp; &nbsp;2,&nbsp; &nbsp;9,&nbsp; &nbsp;5,&nbsp; &nbsp;12,&nbsp; 4,&nbsp; &nbsp;8&nbsp; ];let obj = {};// loop over the first array, if not already in obj, put a zero before addingdepts.forEach((dept,i) => obj[dept] = (obj[dept] || 0) + cnts[i])console.log(obj);

白猪掌柜的

var depts = [ 'A', 'D', 'M', 'G', 'D', 'B', 'D', 'A', 'A' ];var cnts&nbsp; = [&nbsp; 3,&nbsp; &nbsp;7,&nbsp; 15,&nbsp; &nbsp;2,&nbsp; &nbsp;9,&nbsp; &nbsp;5,&nbsp; &nbsp;12,&nbsp; 4,&nbsp; &nbsp;8&nbsp; ];const lkp = depts.reduce((lkp, cur, i) => {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; ...lkp,&nbsp; &nbsp; &nbsp; &nbsp; [cur]: ~~lkp[cur] + cnts[i]&nbsp; &nbsp; }}, {})console.log (lkp)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript