gpt4 book ai didi

javascript - 如何组合具有相同索引的数组对象?

转载 作者:行者123 更新时间:2023-11-30 06:27:03 25 4
gpt4 key购买 nike

我有这个数组对象:

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:修复原始代码..我想?

最佳答案

经过我们在这里的长评论线程,我想这就是您需要的:

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

关于javascript - 如何组合具有相同索引的数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com