var message =message:
[ {n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"在吗555",date:"2010-12-23"},
{n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"回来了吗",date:"2019-12-23"},
{n:"刘云",a:"static/images/ly.jpg",from:"10", to: "1",msg:"回来了:)",date:"2019-12-3"},
{n:"刘云",a:"static/images/ly.jpg",from:"10", to: "1",msg:"给你带了东西",date:"2019-12-23"},
{n:"刘云",a:"static/images/ly.jpg",from:'10', to: "1",msg:"累死了",date:"2012-1-1"},
{n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"在吗555bbbbbb",date:"2010-12-23"},
{n:"刘云",a:"static/images/ly.jpg",from:'10', to: "1",msg:"累死了333333",date:"2012-1-1"},
];
拆分为:
var message =message:
[ [{n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"在吗555",date:"2010-12-23"},
{n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"回来了吗",date:"2019-12-23"}],
[{n:"刘云",a:"static/images/ly.jpg",from:"10", to: "1",msg:"回来了:)",date:"2019-12-3"},
{n:"刘云",a:"static/images/ly.jpg",from:"10", to: "1",msg:"给你带了东西",date:"2019-12-23"},
{n:"刘云",a:"static/images/ly.jpg",from:'10', to: "1",msg:"累死了",date:"2012-1-1"}],
[{n:"jerry",a:"static/images/liuyan.jpg",from:"1", to: "10",msg:"在吗555bbbbbb",date:"2010-12-23"}],
[{n:"刘云",a:"static/images/ly.jpg",from:'10', to: "1",msg:"累死了333333",date:"2012-1-1"}]
];
每次收到对方的新消息,需要另起一行,如果一直是自己说话,内容还在这行里面。
如何用underscore 实现。
只能用 each
了.
var e = [],//保存结果
f = [] ;//保存连续的数据项
_.each(a, function(b){
//如果当前内容是 空
if(f.length === 0){
f = [b];//直接仍进去
}else{
//如果当前的这个 与上一个 一样
if(b.n === f[f.length - 1].n){
//仍进 f 数组里
f.push(b);
}else{//不一样的情况
//将 f 仍进 e中
e.push(f);
//将当前的这个仍到f中
f = [b];
}
}
});
//最后, 如果f里还有内容
if(f.length > 0){
//把剩下的数据仍到 e 里
e.push(f);
}
//输出结果
console.log(JSON.stringify(e, 0 , '\t'))
结果:
[
[
{
"n": "jerry",
"a": "static/images/liuyan.jpg",
"from": "1",
"to": "10",
"msg": "在吗555",
"date": "2010-12-23"
},
{
"n": "jerry",
"a": "static/images/liuyan.jpg",
"from": "1",
"to": "10",
"msg": "回来了吗",
"date": "2019-12-23"
}
],
[
{
"n": "刘云",
"a": "static/images/ly.jpg",
"from": "10",
"to": "1",
"msg": "回来了:)",
"date": "2019-12-3"
},
{
"n": "刘云",
"a": "static/images/ly.jpg",
"from": "10",
"to": "1",
"msg": "给你带了东西",
"date": "2019-12-23"
},
{
"n": "刘云",
"a": "static/images/ly.jpg",
"from": "10",
"to": "1",
"msg": "累死了",
"date": "2012-1-1"
}
],
[
{
"n": "jerry",
"a": "static/images/liuyan.jpg",
"from": "1",
"to": "10",
"msg": "在吗555bbbbbb",
"date": "2010-12-23"
}
],
[
{
"n": "刘云",
"a": "static/images/ly.jpg",
"from": "10",
"to": "1",
"msg": "累死了333333",
"date": "2012-1-1"
}
]
]