计算缺失项后将新数组添加到JSON对象

时间:2019-02-12 19:54:01

标签: javascript jquery json

我有以下json文件

[{"id":5,"num":"n61","mov_date":"2019-02-01T00:00:00","orders":19},
{"id":5,"num":"n61","mov_date":"2019-02-05T00:00:00","orders":12},
{"id":5,"num":"n61","mov_date":"2019-02-08T00:00:00","orders":5},
{"id":5,"num":"n61","mov_date":"2019-02-11T00:00:00","orders":7}]

我想使用JavaScript,jquery添加新项目以结束

[{"id":5,"num":"n61","mov_date":"2019-02-01T00:00:00","orders":19},
{"id":5,"num":"n61","mov_date":"2019-02-02T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-03T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-04T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-05T00:00:00","orders":12},
{"id":5,"num":"n61","mov_date":"2019-02-06T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-07T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-08T00:00:00","orders":5},
{"id":5,"num":"n61","mov_date":"2019-02-09T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-10T00:00:00","orders":0},
{"id":5,"num":"n61","mov_date":"2019-02-11T00:00:00","orders":7}]

可以通过计算日期之间错过的项目数,或者仅计算数字之间的差异来表示日期,即:“ 2019-02-01 T00:00:00”和“ 2019-02- { {1}} T00:00:00“,然后添加3个项目?

4 个答案:

答案 0 :(得分:1)

var items = [
  {"id":5,"num":"n61","mov_date":"2019-02-01T00:00:00","orders":19},
  {"id":5,"num":"n61","mov_date":"2019-02-05T00:00:00","orders":12},
  {"id":5,"num":"n61","mov_date":"2019-02-08T00:00:00","orders":5},
  {"id":5,"num":"n61","mov_date":"2019-02-11T00:00:00","orders":7}
]

var newItems = []

for(var i = 0; i < items.length; i++){
        newItems.push(items[i])
  
	var currentDay = moment(items[i].mov_date)
        var nextDay = currentDay.add(1, 'days');
	
	if(typeof items[i+1] !== 'undefined'){
		var diff = moment(items[i+1].mov_date).diff(currentDay, 'days')
		
		for(var j = 1; j <= diff; j++){
			var newItem = JSON.parse(JSON.stringify(items[i]))
			newItem.mov_date = moment(items[i].mov_date).add(j, 'days').utc(false).format();
			newItem.orders = 0
			newItems.push(newItem)
		}
	}
}

console.log(newItems)
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

答案 1 :(得分:0)

您可以使用Date对象,可以使用其setDate方法对其进行递增,并使用toJSON将其渲染为字符串。然后,当日期字符串与下一个条目匹配时,将其复制,否则将其复制为orders: 0

const data = [{"id":5,"num":"n61","mov_date":"2019-02-01T00:00:00","orders":19},{"id":5,"num":"n61","mov_date":"2019-02-05T00:00:00","orders":12},{"id":5,"num":"n61","mov_date":"2019-02-08T00:00:00","orders":5},{"id":5,"num":"n61","mov_date":"2019-02-11T00:00:00","orders":7}];

const end = new Date(data[data.length-1].mov_date + "Z");
const result = [];
for (let dt = new Date(data[0].mov_date+"Z"), i = 0; dt <= end; dt.setUTCDate(dt.getUTCDate()+1)) {
    result.push({...data[i], ...(dt.toJSON().slice(0,19) === data[i].mov_date ? (i++, {}) : { orders: 0 })});  
}
console.log(result);

答案 2 :(得分:0)

还请检查使用reduce()保留所有道具(包括id)并且仅重置orders并在两者之间设置正确的mov_date的道具。

var items = [{
    "id": 5,
    "num": "n61",
    "mov_date": "2019-02-01T00:00:00",
    "orders": 19
  },
  {
    "id": 5,
    "num": "n61",
    "mov_date": "2019-02-05T00:00:00",
    "orders": 12
  },
  {
    "id": 5,
    "num": "n61",
    "mov_date": "2019-02-08T00:00:00",
    "orders": 5
  },
  {
    "id": 5,
    "num": "n61",
    "mov_date": "2019-02-11T00:00:00",
    "orders": 7
  }
]

const newItems = items.reduce((acc, next) => {

  // first run with early return
  if (!acc.length) {
    return [...acc, next]
  }

  // taking the recent item, to preserve the id and other props
  const prevItem = acc[acc.length - 1];

  // getting diff in days - 1
  const days = moment.utc(next.mov_date).diff(moment.utc(prevItem.mov_date), 'days') - 1;

  // [...Array] is a trick to get mappable arrays without array holes, 
  // but with initialized undefined values, 
  // so we can get the index during map
  const inBetweenValues = [...Array(days)].map((_, dayIndex) => {
    return {
      ...prevItem,
      orders: 0,
      mov_date: moment.utc(prevItem.mov_date).add(dayIndex + 1, 'days').format()
    };
  });

  // merging it all, and moving to the next loop
  return [...acc, ...inBetweenValues, next];
}, [])

console.log(newItems);
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

答案 3 :(得分:0)

这是一种可以为您完成此任务的算法。我用了 Convert JS date time to MySQL datetime用于日期转换。

function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

function toMysqlFormat() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + "T" + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};


var prev = 0;

for( var x = 1; x < obj.length; x++ ){

    if( !obj[x -1].mov_date ){
        continue;
    }

    var tx = Date.parse( obj[x-1].mov_date );
    var diff = ( Date.parse(obj[x].mov_date ) - tx ) / (1000*24*60*60);

    for( var y = 1; y < diff; y++ ){

        obj.splice( x - 1 + y,0, { "id" : 5, "num" : "n61", "mov_date" : toMysqlFormat.bind( new Date( tx + ( y*1000*24*60*60) ) )(), "orders" : 0} );

    }
    x += diff - 1;

}

for( var x = 0; x < obj.length; x++ ){
    console.log( JSON.stringify( obj[x] ) );
}

/* Result :
/* {"id":5,"num":"n61","mov_date":"2019-02-01T00:00:00","orders":19} */
/* {"id":5,"num":"n61","mov_date":"2019-02-02T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-03T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-04T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-05T00:00:00","orders":12} */
/* {"id":5,"num":"n61","mov_date":"2019-02-06T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-07T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-08T00:00:00","orders":5} */
/* {"id":5,"num":"n61","mov_date":"2019-02-09T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-10T00:00:00","orders":0} */
/* {"id":5,"num":"n61","mov_date":"2019-02-11T00:00:00","orders":7} */
*/