在Laravel中,我使用这种方法将集合合并到集合中,并作为一个集合返回。
$collection = $messages->merge($texts)->sortByDesc('created_at')如果我是dd($colection),它将显示集合对象所有组合在一起和排序在一起。
然后,我试图通过ajax将其发送到vue,但是,数据又被分离了。我的目标是这样的:
item: {
messages: [
0: { ... }
1: { ... }
2: { ... }
3: { ... }
],
texts: [
0: { ... }
1: { ... }
]
}这是因为return response()->json('item' => '$collection')再次将它们分隔为消息和文本。
我试图像这样组合它们,但是它覆盖了值(我假设是因为ids是相同的)。
vm item = this;
// in response of ajax get,
.then(function(response) {
var item = response.data.item;
Object.assign(vm.item.messages, vm.item.texts);
});怎样才能正确地将文本组合成信息,并按时间戳对它们进行排序?在第一级对象中,它们都有created_at,如下所示:
messages: [
0: { created_at: ... }
],
texts: [
0: { created_at: ... }
]更新:在icepickle的回答之后,通过连接,我可以将它们合并到消息数组中。现在,当created_at值被转换为字符串时,我遇到了一个问题。以下是一些测试数据。这是我下订单后得到的:
messages: [
0: {
msg: 'hello',
created_at: "2017-10-12 00:48:59"
},
1: {
msg: 'mellow',
created_at: "2017-10-11 16:05:01"
},
2: {
msg: 'meow',
created_at: "2017-10-11 15:07:06"
},
4: {
msg: 'test'
created_at: "2017-10-11 17:13:24"
}
5: {
msg: 'latest'
created_at: "2017-10-12 00:49:17"
}
],发布于 2017-10-12 00:20:54
它不足以concat数组,然后排序吗?
有点像
let result = ([]).concat(item.messages, item.texts);或在es6中
let result = [...item.messages, ...item.texts]然后对结果调用排序。
// in place sort, result will be sorted, and return the sorted array
result.sort((a, b) => a.created_at - b.created_at);
const items = {
messages: [
{
msg: 'hello',
created_at: "2017-10-12 00:48:59"
},
{
msg: 'mellow',
created_at: "2017-10-11 16:05:01"
},
{
msg: 'meow',
created_at: "2017-10-11 15:07:06"
}
],
texts: [
{
msg: 'test',
created_at: "2017-10-11 17:13:24"
},
{
msg: 'latest',
created_at: "2017-10-12 00:49:17"
}
]
};
let result = [...items.messages, ...items.texts].sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
console.log( result );
https://stackoverflow.com/questions/46699435
复制相似问题