gpt4 book ai didi

javascript - 将两个对象合并为一个对象并按时间戳排序

转载 作者:行者123 更新时间:2023-12-03 03:17:34 25 4
gpt4 key购买 nike

在 Laravel 中,我使用了这种方法将集合组合在一起并作为一个集合返回。

$collection = $messages->merge($texts)->sortByDesc('created_at')

如果我dd($collection),它会显示全部组合并排序在一起的 Collection 对象。

然后我尝试通过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);
});

将文本组合成消息并按时间戳对其进行排序的正确方法是什么?他们都在第一层对象中创建了如下的create_at:

messages: [
0: { created_at: ... }
],
texts: [
0: { created_at: ... }
]
<小时/>

更新:在icepickle的回答之后,通过concat,我能够将它们组合在消息数组中。现在,我遇到了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"
}
],

最佳答案

这还不够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 );

关于javascript - 将两个对象合并为一个对象并按时间戳排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46699435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com