Mass subset record objects in javascript
Problem
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
Is there a faster / more elegant way?
Problem courtesy of: Jeroen
Solution
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);
}, {});
});
Solution courtesy of: nautat
Discussion
View additional discussion.