如何将数组的对象与同一索引组合

How do I combine object of arrays with the same index?

本文关键字:索引 组合 对象 数组      更新时间:2024-03-19

我有这个数组对象:

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:我之所以需要它是这种格式,是因为我使用的是CalendarioJQuery插件。数据需要采用特定的格式。

edit3:修复了原始代码。。我想?

在我们这里的长评论线程之后,我想这就是您所需要的:

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;
}