简体   繁体   English

将两个 arrays 组合成键值对,如果键已经存在,则添加值

[英]Combine two arrays into key-value pairs and add values if key already exists

I have two arrays (a & b) that I want to combine into one array (obj) with key-value pairs.我有两个 arrays(a 和 b),我想将它们组合成一个带有键值对的数组(obj)。 How can I make it so that if obj does not include key, add that key and corresponding value to obj, but if obj already has that key, add the value of duplicate key to original key value?我怎样才能做到,如果 obj 不包含键,则将该键和相应的值添加到 obj,但是如果 obj 已经具有该键,则将重复键的值添加到原始键值?

var a = ["red", "green", "red", "blue"]
var b = [2, 4, 3, 1]

desired obj = {["red", 5], ["green", 4], ["blue", 1]}

I know keys need to be unique in an array so if I combine the two arrays outright like below, the duplicate keys will disappear, but I'm not sure how to handle the values of duplicate keys and add all values of the same key together.我知道键在数组中必须是唯一的,所以如果我像下面这样直接组合两个 arrays,重复键将消失,但我不确定如何处理重复键的值并将同一键的所有值加在一起.

var obj = {};
for (var i=0; i<a.length; i++) {
    obj[a[i]] = b[i]
}

You need to check if the key already exists in the object so you don't overwrite the previous value您需要检查 object 中是否已存在密钥,以免覆盖先前的值

 var a = ["red", "green", "red", "blue"] var b = [2, 4, 3, 1] var obj = {}; for (var i=0; i<a.length; i++) { // if it doesn't exist assign value 0 to it, otherwise use existing value obj[a[i]] = obj[a[i]] || 0; // then add the new value obj[a[i]] += b[i]; } console.log(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM