Javascript - 在对象数组中搜索和匹配数据的更好方法?

时间:2016-10-11 09:23:57

标签: javascript arrays for-loop ecmascript-6

有没有更好的方法来做下面的事情?我想在particles数组中查找与timestamp数组中搜索日期的索引/位置匹配的数据。

我的示例数据:

var data = {
    particles: ['1.0',
    '1.1',
    '1.2',
    '2.0',
    '2.1',
    '2.2',
    '3.0',
    '3.1'],

    timestamp: ['2016-10-10',
    '2016-10-10',
    '2016-10-10',
    '2016-10-11',
    '2016-10-11',
    '2016-10-11',
    '2016-10-13',
    '2016-10-13'],
};

我的代码:

var find = '2016-10-11';
var lookup = {};

var timestamp = [];
var index = [];
for (var key in data.timestamp) {
    if (data.timestamp[key] === find) {
        timestamp.push(data.timestamp[key]);
        index.push(key);
    }
}
console.log(timestamp);
// --> ["2016-10-11", "2016-10-11", "2016-10-11"]

var particles = [];
for (var key in data.particles) {
    // Check if the key is in the index.
    if (index.indexOf(key) > -1) {
        particles.push(data.particles[key]);
    }
}
console.log(particles);
// --> ["2.0", "2.1", "2.2"]

lookup.particles = particles;
lookup.timestamp = timestamp;

console.log(lookup);

结果:

{
    particles: [
    '2.0',
    '2.1',
    '2.2'
    ],

    timestamp: [
    '2016-10-11',
    '2016-10-11',
    '2016-10-11'],
}

我会在timestampparticles中拥有数千个的项目,所以我认为上面的循环可能会在将来导致一些性能问题。

另外,我可能在期货中的对象中有更多的键:

{
   particles1: [...],
   particles2: [...],
   particles3: [...],
   timestamp: [...]
}

所以我手动查看匹配数据可能不是一个好方法。

有更好的想法吗?

timestamp始终是数据中的固定密钥。

我更喜欢 vanilla Javascript解决方案。

1 个答案:

答案 0 :(得分:3)

您可以先获取索引,然后获取每个属性的结果集

var data = { particles: ['1.0', '1.1', '1.2', '2.0', '2.1', '2.2', '3.0', '3.1'], timestamp: ['2016-10-10', '2016-10-10', '2016-10-10', '2016-10-11', '2016-10-11', '2016-10-11', '2016-10-13', '2016-10-13'] },
    find = '2016-10-11',
    lookup = {},
    indices = [];


data.timestamp.forEach(function (a, i) {
    a === find && indices.push(i);
});

Object.keys(data).forEach(function (k) {
    lookup[k] = indices.map(function (i) {
        return data[k][i];
    });
});
 
console.log(lookup);