Lodash es una librería de JavaScript con muchísimas utilidades, sobre todo para gestionar arrays. Es una heredera aventajada de otra librería famosas Underscore.
Algunos ejemplos de Lodash
Devolver el valor de una clave del primer item de un array que es el valor de otra clave:
// Obtener el nombre del primer hermano de cada persona
var personas = [{
"nombre": "Jose Luis",
"hermanos": [{"nombre":"David"}, {"nombre": "Sonia"}]
}, {
"nombre": "Alfonso Manuel",
"hermanos": [{"nombre":"Gustavo"}, {"nombre": "Juan"}]
}];
// Array's map method.
var nombres = personas.map(function(item){
return item.hermanos[0].nombre;
});
// [ 'David', 'Gustavo' ]
// Lodash
var nombresBis = _.map(personas, 'hermanos[0].nombre');
// [ 'David', 'Gustavo' ]
var users = [
{ firstName: "Ldmarz", lastName: "martinez", age: 28, gender: "male" },
{ firstName: "Suli", lastName: "bern", age: 5, gender: "female" },
{ firstName: "Marianis", lastName: "Carrey", age: 54, gender: "male" },
{ firstName: "Jhon", lastName: "carret", age: 40, gender: "female" }
];
var user = _.find(users, { name: "ldmarz", gender: "male" });
// { firstName: "Ldmarz", lastName: "martinez", age: 28, gender: "male" },
var childUser = _.find(users, function(user) {
return user.age < 18;
});
// { firstName: "Suli", lastName: "bern", age: 5, gender: "female" }
var users = [
{ firstName: "Ldmarz", lastName: "martinez", age: 28, gender: "male" },
{ firstName: "Suli", lastName: "bern", age: 5, gender: "female" },
{ firstName: "Marianis", lastName: "Carrey", age: 54, gender: "female" },
{ firstName: "Jhon", lastName: "carret", age: 40, gender: "male" }
];
var femaleUsers = _.filter(users, function(user) {
return user.gender === 'female'
});
// femaleUsers ===> [
// { firstName: "Suli", lastName: "bern", age: 5, gender: "female" },
// { firstName: "Marianis", lastName: "Carrey", age: 54, gender: "female" }
// ];
var someNiceObject = { hello: { someDeepKey: "hello" } };
_.set(someNiceObject, "hello.items[0]", "An item");
// here items was added safely
// someNiceObject === { hello: { someDeepKey: "hello", items: ["An item"] } }
//Here we can access to a not existing key getting a default value instead
var name = _.get(someNiceObject, "someNotExistingKey", "Ldmarz");
// name => Ldmarz
const someArray = [1, 1, 3]
const cleanArray = _.uniq(someArray);
// cleanArray === [1, 3]
const someDirtyArray = [0, 1, false, 2, '', 3];
const cleanedArray = _.compact(someDirtyArray);
// cleanedArray => [1, 2, 3]
Deja una respuesta