Skip to content

Instantly share code, notes, and snippets.

@muratgozel
Created August 8, 2017 08:36
Show Gist options
  • Save muratgozel/76f516dec675720e0e0ef75b280a44be to your computer and use it in GitHub Desktop.
Save muratgozel/76f516dec675720e0e0ef75b280a44be to your computer and use it in GitHub Desktop.
Creates a new javascript object from bigger javascript object by taking certain properties from it.
/*
* Creates a new javascript object from bigger javascript object by taking certain properties from it.
*
* @param {object} input - Main javascript object
* @param {array} keys - Keys that will be used to create a new object.
*/
Object.prototype.extract = function extract(input, keys) {
return Object.prototype.toString.call(input) === '[object Object]'
? Object.keys(input)
.filter(
k =>
Array.isArray(keys)
? keys.indexOf(k) !== -1
: typeof keys == 'string'
? [keys].indexOf(k) !== -1
: typeof keys == 'number'
? [String(keys)].indexOf(k) !== -1
: false
)
.reduce((memo, key) => {
memo[key] = input[key]
return memo
}, {})
: {}
}
// Test Cases
const obj1 = {
a: 'A',
b: 'B',
c: 'C',
d: 'D',
8: 'Eight',
0: 'Zero'
}
obj1.extract(obj1, ['a', 'd']) === { a: 'A', d: 'D' }
obj1.extract(obj1, ['t']) === {}
obj1.extract(obj1, '8') === { '8': 'Eight' }
obj1.extract(obj1, 8) === { '8': 'Eight' }
obj1.extract(undefined) === {}
obj1.extract() === {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment