Transform JavaScript objects.
- Map and filter objects as easily as arrays
- Methods can be chained by default
- 417 bytes gzipped
npm install --save obex
or
yarn add obex
var obex = require('obex');
var regularObject = { propertyName: 'value' };
var transformableObject = obex(regularObject);
An obex
object is just like a regular JavaScript object, but it can be transformed using methods like filter
and map
to make object manipulation simpler. These methods can be chained together because obex
adds non-enumerable properties to the given raw JavaScript object.
obex(object)
- object: plain old JavaScript object to become transformable using
obex
methods.- Return:
obex
object
- Return:
filter(testFunction)
- testFunction: function to test each key-value entry in the object.
- Parameters: (key, value)
- Return:
true
to keep the entry,false
otherwise.
obex({ a: 3, b: 6 })
.filter(function(key, value) {
return value < 5;
});
// { a : 3 }
map(keyMapper, valueMapper)
- keyMapper: function to map old keys to new keys.
- Parameters: (key [, value])
- Return: replacement key for this entry.
- valueMapper: function to map old values to new values.
- Parameters: (value [, key])
- Return: replacement value for this entry.
obex({ a: 3, b: 6 }).map(
function(key) {
return key + key;
},
function(value) {
return value * 2;
}
);
// { aa: 6, bb: 12 }
mapKeys(keyMapper)
- keyMapper: function to map old keys to new keys.
- Parameters: (key [, value])
- Return: replacement key for this entry.
obex({ a: 3, b: 6 }).mapKeys(function(key, value) {
return key + key + value;
});
// { aa3: 3, bb6: 6 }
mapValues(valueMapper)
- valueMapper: function to map old values to new values.
- Parameters: (value, [, key])
- Return: replacement value for this entry.
function square(x) { return x * x };
obex({ a: 3, b: 6 }).mapValues(square);
// { a: 9, b: 36 }
toArray(entryMapper)
- entryMapper: function to map key-value pairs to array elements,
- Parameters: (key, value)
- Return: array of elements mapped from key-value pairs
obex({ a: 1, b: 2 }).toArray(function(key, value) {
return key + value;
});
// ['a1', 'b2']
keys()
Returns an array containing only the object's keys
obex({ a: 1, b: 2 }).keys();
// ['a', 'b']
values()
Returns an array containing only the object's values
obex({ a: 1, b: 2 }).values();
// [1, 2]
raw()
Converts back to a plain old JavaScript object.
var a = obex({}).filter().map();
var b = a.raw();
var c = b.filter(); // Error