If you want to extract specific properties from an object, you can simply use the reduce method and provide an empty Object
as the initial value. During each iteration, copy the desired property from the original object (obj
) to the accumulator and return it.
The first version below adds all elements that are present in the attrs
array:
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 }));
The second version only includes 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 a shorter arrow function version for the same operation:
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 }));
By using the reduce
method directly on the array, there's no need to use Object.keys
or Array.prototype.filter
to achieve the desired result.