1

我有两个数组如下。

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

我如何将它变成一个关联数组,其中 idOne 是键,counts 是值?

4

3 回答 3

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);
}
于 2013-03-29T21:29:10.417 回答
1

您必须使用一个对象来完成此操作:

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

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

obj['6']; // -> 1
于 2013-03-29T21:27:04.040 回答
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);
});
于 2013-03-29T21:48:32.293 回答