Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
pluck supports keypaths
  • Loading branch information
tjmehta committed May 25, 2014
1 parent 1f67c9e commit 6241bd8
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 5 deletions.
11 changes: 11 additions & 0 deletions README.md
Expand Up @@ -251,6 +251,17 @@ pluck(obj, 'foo'); // 1

// use it with array.map
[obj, obj, obj].map(pluck('foo')); // [1, 1, 1]

// supports keypaths by default
var obj = {
foo: {
bar: 1
},
'foo.bar': 2
};

pluck(obj, 'foo.bar'); // 1
pluck(obj, 'foo.bar', false); // 2
```

## License
Expand Down
17 changes: 12 additions & 5 deletions pluck.js
Expand Up @@ -3,28 +3,35 @@
*/

var isObject = require('./is-object');
var exists = require('./exists');
var keypather = require('keypather')();

/**
* Functional version of obj[key], returns the value of the key from obj.
* When only a key is specified pluck returns a partial-function which accepts obj.
* @function module:101/pluck
* @param {object} [obj] - object from which the value is plucked
* @param {string|array} key - key of the value from obj which is returned
* @param {boolean} [isKeypath=true] - specifies whether the key is a keypath or key
* @return {*|function} The value of the key from obj or Partial-function pluck (which accepts obj) and returns the value of the key from obj
*/
module.exports = function (obj, key) {
module.exports = function (obj, key, isKeypath) {
if (!isObject(obj)) {
isKeypath = key;
key = obj;
return function (obj) {
return pluck(obj, key);
return pluck(obj, key, isKeypath);
};
}
else {
return pluck(obj, key);
return pluck(obj, key, isKeypath);
}
};

function pluck (obj, key) {
function pluck (obj, key, isKeypath) {
key = Array.isArray(key) ? key[0] : key;
return obj[key];
isKeypath = exists(isKeypath) ? isKeypath : true;
return isKeypath ?
keypather.get(obj, key):
obj[key];
}
31 changes: 31 additions & 0 deletions test/test-pluck.js
Expand Up @@ -53,4 +53,35 @@ describe('pluck', function () {
]);
done();
});
describe('isKeypath', function() {
var objs = [{
foo: {
bar: 1
},
'foo.bar': 2
}];
var obj = objs[0];
describe('true and default', function (done) {
it('should pluck a keypath from an object', function (done) {
expect(pluck(obj, 'foo.bar')).to.equal(1);
expect(pluck(obj, 'foo.bar', true)).to.equal(1);
done();
});
it('should pluck keypaths from objects in an array when used with map', function (done) {
expect(objs.map(pluck('foo.bar'))).to.eql([1]);
expect(objs.map(pluck('foo.bar', true))).to.eql([1]);
done();
});
});
describe('false', function (done) {
it('should pluck a key from an object', function (done) {
expect(pluck(obj, 'foo.bar', false)).to.equal(2);
done();
});
it('should pluck keys from objects in an array when used with map', function (done) {
expect(objs.map(pluck('foo.bar', false))).to.eql([2]);
done();
});
});
});
});

0 comments on commit 6241bd8

Please sign in to comment.