2016-10-11 42 views
1

有没有更好的方法做下面的事情?我想查找particles阵列中的数据,该数据与timestamp阵列中的搜索日期的索引/位置相匹配。Javascript - 在对象数组中搜索和匹配数据的更好方法?

我的样本数据:

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'], 
} 

我将在timestamp上千项particles所以我觉得在ma上方循环会在未来造成一些性能问题。

而且,我可能会在物体多个键期货:

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

所以我手动寻找匹配的数据可能不会去的好方法。

有什么更好的点子?

timestamp始终是数据中的一个固定键。

我更喜欢香草 Javascript解决方案。

+0

你是什么意思'设置得match'指数?这些阵列的共同点是什么? – Weedoze

+1

你是否控制了如何生成数组? – Sergeon

+0

@Sergeon是的,我愿意。 – laukok

回答

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);

+1

谢谢。它看起来比我的好! – laukok

相关问题