在JavaScript的2多维数组的元素结合起来 [英] Combine elements from two multidimensional arrays in JavaScript

查看:135
本文介绍了在JavaScript的2多维数组的元素结合起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个数组在JavaScript中:

I have the following two arrays in JavaScript:

"total":[[1370923200000,"66"],[1371009600000,"42"],[1371096000000,"23"]]

"successful":[[1370923200000,"5"],[1371096000000,"2"],[1371182400000,"0"]]

我想将它们组合成一个阵列/对象,它看起来是这样的:

I'd like to combine them into one array / object which looks something like this:

{date:1370923200000, total:"66", successful:"5"},
{date:1371009600000, total:"42"},
{date:1371096000000, total:"23", successful:"2"},
{date:1371182400000, successful:"0"}

我试过多种不同的解决方案,通过两个数组循环,但我似乎无法找出一个优雅的解决方案。

I've tried multiple different solutions, looping through both arrays, but I can't seem to figure out an elegant solution.

推荐答案

在这里,您有:

var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var successful = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var combined = {};

for(var i=0; i<total.length; i++){
    combined[total[i][0]] = {date: total[i][0], total: total[i][1]};
}

for(var i=0; i<successful.length; i++){
    if(successful[i][0] in combined){
        combined[successful[i][0]].successful = successful[i][1];
    }
    else{
        combined[successful[i][0]] = {
            date: successful[i][0], successful: successful[i][1]
        };
    }
}

var result = [];
for(var key in combined){
    result.push(combined[key]);
}
alert(result.toSource());

和工作小提琴 http://jsfiddle.net/eRjeZ/

这篇关于在JavaScript的2多维数组的元素结合起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆