5

我有两个数组,我试图比较并创建第三个

我的第一个数组:

sevenDays = ["04","05","06","07","08","09","10"];

我的第二个数组:

   json[0] =  [Object{day="04",value="5"}, Object { day="05",value="8"}, Object { day="09",value="9"}]

我想要得到的是:

 [[04,5],[05,8],[06,0],[07,0],[08,0],[09,9],[10,0]]

我试过这样

var desiredArray= [];                           
$.each(sevenDays, function (i, v) {
   val= 0;
     if (json[0][i].value) val = json[0][i].value;
     desiredArray[i] = [v, val]
}); 


 [[04,5],[05,8],[06,9],[07,0],[08,0],[09,0],[10,0]] //output
4

2 回答 2

5

您当前正在将 index iin的值与 index of处的对象sevenDays的属性进行比较,但这不正确,因为顺序不匹配。的值位于索引 2 in但位于索引 5 in 。valueijson[0]09json[0]09sevenDays

您需要遍历sevenDays,并为每次迭代遍历json[0]以找到匹配的对象,如下所示:

var desiredArray = [];

$.each(sevenDays, function (i, day) {
    val = 0;
    $.each(json[0], function(j, value) {
        if(day == value.day)
            val = value.value;
    });
    desiredArray[i] = [day, val];
});

看看这个工作演示

于 2013-03-05T12:52:24.000 回答
0

考虑您的第二个数组以正确的 json 格式......

你可以这样做

var data[] =["",""]
for(value in sevenDays)
{
for(Object in json[0])
{
if(Object.hasOwnProperty(data[value])
{
     // do ur stuff here :)
}
else
{
     //do the other stuff here :)
}
}
}
于 2013-03-05T12:54:03.613 回答