gpt4 book ai didi

Javascript for/in 循环 - 连接来自两个不同对象的项目?

转载 作者:行者123 更新时间:2023-11-28 14:55:34 25 4
gpt4 key购买 nike

我有下面这些数据集,我想连接每组中的数据:

    var data = {};
var datasets = [
{"_id":"58d6c806d7c80d5d44a35204","particles":{"timestamp":[1490470918708,1490470962915,1490470967186],"Particles":["108","108","109"]}},
{"_id":"58d6caf62552b75f26f56f91","particles":{"timestamp":[1490471670888,1490473309103],"Particles":["109","100"]}}
];

datasets.forEach(function(dataset, index) {
for (var key in dataset.particles) {
data[key] = dataset.particles[key];
}
});
console.log(data);

结果:

{ timestamp: [ 1490471670888, 1490473309103 ],
Particles: [ '109', '100' ] }

他们没有加入。我追求的结果:

 { timestamp: [ 1490470918708,1490470962915,1490470967186, 1490471670888, 1490473309103 ],
Particles: [ '108','108','109', '109', '100' ] }

有什么想法吗?

编辑

对于数据来说,concatpush 更快吗?

最佳答案

您必须连接数组,而不仅仅是重新分配值。

var data = {};
var datasets = [
{"_id":"58d6c806d7c80d5d44a35204","particles":{"timestamp":[1490470918708,1490470962915,1490470967186],"Particles":["108","108","109"]}},
{"_id":"58d6caf62552b75f26f56f91","particles":{"timestamp":[1490471670888,1490473309103],"Particles":["109","100"]}}
];

datasets.forEach(function(dataset, index) {
for (var key in dataset.particles) {

// Check if key already exists.
if( data[key] === undefined )
data[key] = [];

// Add current timestamps.
data[key] = data[key].concat(dataset.particles[key]);
}
});
console.log(data);

关于Javascript for/in 循环 - 连接来自两个不同对象的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022252/

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