取两个数组,使它们成为键 - 值对

时间:2013-03-29 21:23:00

标签: javascript jquery

我有两个数组如下。

idOne =  ["6", "6", "11"]
counts =  ["2", "1", "1"]

如何将此作为关键数组,并将idOne作为关键并计算为值?

3 个答案:

答案 0 :(得分:3)

(根据您的评论更新)

var totalsByID = {};
for(var i = 0; i < idOne.length; i++) {
   var id = idOne[i];
   var count = parseInt(counts[i]);
   if(totalsByID[id] === undefined) {
      // We have no entry for this ID, so create one
      totalsByID[id] = count;
   } else {
      // We already have an entry for this ID, so we need to add our current count to it
      totalsByID[id] += count;
   }
}

plalx建议了一个包含阵列进行测试的替代结构:

var idOne = ["6", "6", "11"],
    counts = ["2", "1", "1"],
    totalsById = {},
    i = 0,
    len = idOne.length,
    k;

for(; i < len; i++) {
   k = idOne[i];

   //initialize the total to 0
   totalsById[k] = totalsById[k] || 0;

   //you could remove the parseInt call if your count values were numbers instead of strings
   totalsById[k] += parseInt(counts[i], 10);
}

答案 1 :(得分:1)

您必须使用一个对象来完成此任务:

var obj = {};
for(var i=0, l=idOne.length; i<l; i++){
  obj[idOne[i]] = counts[i];
}

然后您可以通过以下方式访问它:

obj['6']; // -> 1

答案 2 :(得分:1)

试试这个:

idOne = ["6", "6", "11"]
counts = ["2", "1", "1"]

var dict = []; // create an empty array
$.each(idOne, function (index, value) {
    dict.push({
        key: idOne[index],
        value: counts[index]
    });
});

console.log(dict);

您可以像这样访问键值对:

$.each(dict, function (index, data) {
    console.log(data.key + " : " + data.value);
});