如何将数组对象与相同的索引组合在一起?

时间:2013-12-05 18:17:48

标签: javascript

我有这个数组的对象:

var a = {1: "one", 2: "two", 3: "three"};

这一个

var b = {1: "ONE", 2: "TWO", 4: "four"};

我需要将两者结合起来,所以输出就像这样:

var c = {1: "oneONE", 2: "twoTWO", 3:"three", 4: "four"};

要让这个工作起来,我遇到了很多麻烦。请帮忙!

编辑: 好的,所以我对问题的简化没有多大意义..

我正在使用Firebase存储数据。

   var dates = [];
   var ids = [];
   snapshot.forEach(function(childSnapshot) { //makes raw data array
   var date = childSnapshot.val().date;
   var id = childSnapshot.val().task_id;

   dates.push(date);
   ids.push(id);          
   });

   function cal_list(names, values) { // makes the array read
         var result = [];
         for (var i = 0; i < names.length; i++){
          if(result[names[i]] === undefined) {
              result[names[i]] = values[i];
          }
          else {
              // How do I add the values[i] to the existing date index?
              // if i used result[names[i]] = values[i] -- it only holds a single date. I need a way to add the value to an existing date.


          }

            };

  var calendar_list = cal_list(dates, ids);
  populateCal(calendar_list); //Successfully populates cal, but i'm missing tasks.
  console.log(result);

控制台显示: {12-04-2013: "<a href="/task/-J9oFhGluCZsLBXFof8c">Test</a>", 12-05-2013: "<a href="/task/-J9PUCxYe2C5gJg7t7gX">Write a blog post</a>", 12-06-2013: "<a href="/task/-J9PUCxYe2C5gJg7t7gX">Write a blog post</a>"}

它覆盖索引,只存储最后一次运行的值。我需要一种方法来组合类似日期的值,因此最终结果如下所示:

{12-04-2013: "<a href="/task/-J9oFhGluCZsLBXFof8c">Test</a><a href="#">SECOND TASK</a><a href="#">THIRD TASK</a>", 12-05-2013: "<a href="/task/-J9PUCxYe2C5gJg7t7gX">Write a blog post</a>", 12-06-2013: "<a href="/task/-J9PUCxYe2C5gJg7t7gX">Write a blog post</a>"}

edit2:我需要它采用这种格式的原因是因为我正在使用Calendario JQuery插件。数据需要采用特定格式。

edit3:修复原始代码..我想?

1 个答案:

答案 0 :(得分:0)

经过我们在这里的长评论帖后,我想这就是你需要的:

function cal_list(names, values) {
    var result = [], i, n, doubleFound;
    for (i = 0; i < names.length; i++){
        /* If you want to avoid double keys (only the first-one will stay):
        for (n = 0; n < result.length; n++) {
            if (names[i] in result[n]) {
                doubleFound = true;
                break;
            }
        if (doubleFound) {
            doubleFound = false;
            continue;
        }
       */
        result[i] = {};
        result[names[i]] = values[i];
    }
    return result;
}