Just use reduce and pass in an empty Object. In each iteration just copy the property from obj to the accumulator and then return it.
Below version adds all elements that exist in attrs
function test(attrs, obj) {
return attrs.reduce(function(accumulator, currentValue) {
accumulator[currentValue] = obj[currentValue];
return accumulator;
}, {});
}
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2 }));
Below version only adds elements that exist in both attrs and obj
function test(attrs, obj) {
return attrs.reduce(function(accumulator, currentValue) {
if(obj.hasOwnProperty(currentValue))
accumulator[currentValue] = obj[currentValue];
return accumulator;
}, {});
}
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2 }));
Here is the short arrow version
function test(attrs, obj) {
return attrs.reduce((a, c) => { a[c] = obj[c]; return a; }, {});
}
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b'], { 'a': 1, 'b': 2, 'c': 3 }));
console.log(test(['a', 'b', 'c'], { 'a': 1, 'b': 2 }));
And tada. No need to use Object.keys or Array.prototype.filter if you just reduce the array instead of the properties of the object.