原生js中json时间相同的放到一起

第一种
这里写图片描述

var a=[{
    "id":1,
    "type":3,
    "date":"2018-03-26 23:44:15"
},{
    "id":2,
    "type":1,
    "date":"2018-03-26 23:44:15"
},{
   "id":3,
    "type":5,
    "date":"2018-03-26 23:44:18"
}]
var b={}
a.forEach(v=>{
    b[v.date]||(b[v.date]=[])
    b[v.date]&&b[v.date].push(v)
})
console.log(b)

VM147521:19 {2018-03-26 23:44:15: Array(2), 2018-03-26 23:44:18: Array(1)}2018-03-26 23:44:15: (2) [{…}, {…}]0: {id: 1, type: 3, date: "2018-03-26 23:44:15"}1: {id: 2, type: 1, date: "2018-03-26 23:44:15"}length: 2__proto__: Array(0)2018-03-26 23:44:18: [{…}]__proto__: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()get __proto__: ƒ __proto__()set __proto__: ƒ __proto__()
undefined

第二种
这里写图片描述

var orders=[{
    "id":1,
    "type":3,
    "date":"2018-03-26 23:44:15"
},{
    "id":2,
    "type":1,
    "date":"2018-03-26 23:44:15"
},{
   "id":3,
    "type":5,
    "date":"2018-03-26 23:44:18"
}]
var b={};
var New=new Array();
orders.forEach(v=>{
    /*b[v.date]||(b[v.date]=[])
    b[v.date]&&b[v.date].push(v)*/
    !b[v.date]?(b[v.date]=[v]):b[v.date].push(v);
    //b[v.date]?b[v.date].push(v):b[v.date]=[v]
})
var i=0;
for(var o in b){
    New[i]={
        "time":o,
        "oarr":b[o]
    }
    i++;
}
console.log(New)

VM147520:28 (2) [{…}, {…}]0: oarr: (2) [{…}, {…}]0: {id: 1, type: 3, date: "2018-03-26 23:44:15"}1: {id: 2, type: 1, date: "2018-03-26 23:44:15"}date: "2018-03-26 23:44:15"id: 2type: 1__proto__: Objectlength: 2__proto__: Array(0)time: "2018-03-26 23:44:15"__proto__: Object1: oarr: [{…}]0: {id: 3, type: 5, date: "2018-03-26 23:44:18"}length: 1__proto__: Array(0)time: "2018-03-26 23:44:18"__proto__: Objectlength: 2__proto__: Array(0)
undefined

猜你喜欢

转载自blog.csdn.net/qq_29132907/article/details/79711850