1.0.0 • Published 9 years ago

object-only-value v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
9 years ago

object-only-value

Build Status

Assert that object has only one key and return its value.

For when you want to do obj[Object.keys(obj)[0]], but know that if obj somehow ended up with zero or more keys than one, it'd end in a disaster.

Literally:

var assert = require('assert');

module.exports = function(obj) {
  var keys = Object.keys(obj);
  assert.equal(keys.length, 1, 'Object should have exactly one key');
  return obj[keys[0]];
};

Installation

npm install object-only-value

Usage

var onlyValue = require('object-only-value');
var obj = { foo: 42 };
var theValue = onlyValue(obj); // => 42

obj = {};
theValue = onlyValue(obj); // => throws

obj = { foo: 42, bar: 24 };
theValue = onlyValue(obj); // => throws