I am looking for the most efficient way to extract a subset of elements from a javascript object. Suppose I have many records in the form of javascript objects
var records = [
{ foo: 123, bar: 456, baz: 789, boo: [1,2,3] },
{ foo: 345, bar: 754, baz: 853, boo: [4,3,2] },
{ foo: 321, bar: 234, baz: 443, boo: [5,2,1] }
]
And for each of these objects I want to extract the same keys, which are stored in an array, e.g.
var keys = ["bar", "boo"]
The native way to do so would be along the lines of
out = [];
for(var i = 0; i < records.length; i++){
out[i] = {};
for(var j = 0; j < keys.length; j++){
var field = keys[j];
out[i][field] = records[i][field]
}
}
console.log(out)
Is there a faster / more elegant way?
I can't think of a better Big O notation for your problem, but looking at the current data, a good algoritm may not be your primary focus?
In ECMA-script 5 the base Object contains a keys method:
a = {a: '1', b: '2', c: '3'}
Object.keys(a)
// [ 'a', 'b', 'c' ]
Not sure about speed, but a more concise notation could be (assuming all keys are present in each record):
var out = records.map(function(v) {
return keys.reduce(function(o, k) {
return (o[k] = v[k], o);
}, {});
});