Appearance
Objects
Similar to arrays, Underscore provides many functions specifically for objects.
keys / allKeys
keys()
conveniently returns all the keys of an object, excluding those inherited from the prototype chain:
javascript
function Student(name, age) {
this.name = name;
this.age = age;
}
let xiaoming = new Student('Ming', 20);
_.keys(xiaoming); // ['name', 'age']
allKeys()
includes keys from the prototype chain as well:
javascript
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.school = 'No.1 Middle School';
let xiaoming = new Student('Ming', 20);
_.allKeys(xiaoming); // ['name', 'age', 'school']
values
Similar to keys()
, values()
returns all values of the object, excluding those inherited from the prototype chain:
javascript
let obj = {
name: 'Ming',
age: 20
};
_.values(obj); // ['Ming', 20]
mapObject
mapObject()
is the map version for objects:
javascript
let obj = { a: 1, b: 2, c: 3 };
// Note the function signature, value first, key second:
_.mapObject(obj, (v, k) => 100 + v); // { a: 101, b: 102, c: 103 }
invert
invert()
swaps each key-value pair in an object:
javascript
let obj = {
Adam: 90,
Lisa: 85,
Bart: 59
};
_.invert(obj); // { '59': 'Bart', '85': 'Lisa', '90': 'Adam' }
extend / extendOwn
extend()
merges multiple objects into the first one and returns it:
javascript
let a = {name: 'Bob', age: 20};
_.extend(a, {age: 15}, {age: 88, city: 'Beijing'}); // {name: 'Bob', age: 88, city: 'Beijing'}
// The contents of variable a are also changed:
a; // {name: 'Bob', age: 88, city: 'Beijing'}
If there are duplicate keys, the values from later objects will overwrite those from earlier ones. extendOwn()
works similarly but ignores inherited properties.
clone
To copy an object, you can use clone()
, which creates a shallow copy:
javascript
let source = {
name: 'Ming',
age: 20,
skills: ['JavaScript', 'CSS', 'HTML']
};
let copied = _.clone(source);
console.log(JSON.stringify(copied, null, ' '));
Note: clone()
performs a shallow copy, meaning that for identical keys, the values refer to the same object:
javascript
source.skills === copied.skills; // true
Modifying source.skills
will affect copied.skills
.
isEqual
isEqual()
performs a deep comparison of two objects and returns true
if they are identical:
javascript
let o1 = { name: 'Bob', skills: { Java: 90, JavaScript: 99 }};
let o2 = { name: 'Bob', skills: { JavaScript: 99, Java: 90 }};
o1 === o2; // false
_.isEqual(o1, o2); // true
isEqual()
also works for arrays:
javascript
let o1 = ['Bob', { skills: ['Java', 'JavaScript'] }];
let o2 = ['Bob', { skills: ['Java', 'JavaScript'] }];
o1 === o2; // false
_.isEqual(o1, o2); // true
For more complete functions, please refer to the Underscore documentation: https://underscorejs.org/#objects