Javascript循环并插入新对象

时间:2016-04-21 19:06:02

标签: javascript jquery json loops while-loop

我用ajax获取这些数据:

[{"id":125,"price":225,"start":"Tue, 26 Apr 2016 00:00:00 +0000","user_id":8},{"id":124,"price":200,"start":"Wed, 27 Apr 2016 00:00:00 +0000","user_id":8},{"id":121,"price":67,"start":"Sat, 23 Apr 2016 00:00:00 +0000","user_id":8},{"id":114,"price":45,"start":"Sun, 08 May 2016 00:00:00 +0000","user_id":9},{"id":113,"price":55,"start":"Sun, 24 Apr 2016 00:00:00 +0000","user_id":8},{"id":111,"price":55,"start":"Wed, 01 Jun 2016 00:00:00 +0000","user_id":11},{"id":110,"price":53,"start":"Fri, 03 Jun 2016 00:00:00 +0000","user_id":8},{"id":107,"price":53,"start":"Wed, 03 Aug 2016 00:00:00 +0000","user_id":8},{"id":106,"price":55,"start":"Mon, 01 Aug 2016 00:00:00 +0000","user_id":8},{"id":105,"price":53,"start":"Tue, 16 Aug 2016 00:00:00 +0000","user_id":8},{"id":104,"price":55,"start":"Thu, 21 Apr 2016 00:00:00 +0000","user_id":11},{"id":101,"price":57,"start":"Wed, 17 Aug 2016 00:00:00 +0000","user_id":8}]

因此您可以看到有start个数据。 我也有:

var start = '04/17/2016 12:00 am';
var end = '09/20/2016 12:01 am';

现在我需要每天从startend进行循环,检查是否将日期(日期)激活到json中,如果没有将新数据添加到json中:

{"id":0,"price":100,"start":"DATE","user_id":0}

最好的方法是什么?

更新 我从头到尾创建了一个带日期的新内容,但现在我需要将json放入新数组:http://jsbin.com/qekijumobe/edit?js,output

1 个答案:

答案 0 :(得分:0)

我的另一个答案是错误的,这是我之后提出的:

首先,创建一个foreach循环,循环遍历数组中的所有对象

for (var obj of objArray) {} //Use "of" instead of "in" tk get the values and not the indices

然后,在这个循环中,检查对象的每个字段,如果它们相同,abd,如果它们相同,则打破循环,否则,如果没有匹配的对象,将它推入阵列。

function isInArray(yourObj) {
    for (var obj of objArray) {
        if (obj.id == yourObj.id && obj.start == yourObj.start && obj.price == yourObj.price && obj.user_id == yourObj.user_id)
             return true;
     }
    return false;
}