¿Cómo filtrar las teclas de un objeto con lodash?


Tengo un objeto con algunas claves, y quiero mantener solo algunas de las claves con su valor?

Lo intenté con filter:

var data = {
  "aaa":111,
  "abb":222,
  "bbb":333
};

var result = _.filter(data, function(value, key) {
  return key.startsWith("a");
})

console.log(result);

Pero imprime una matriz:

[111, 222]

Que no es lo Que quiero.

¿Cómo hacerlo con lodash? ¿O algo más si Lodash no funciona?

Demostración en vivo: http://jsbin.com/moqufevigo/1/edit?js, output

Author: Freewind, 2015-06-09

4 answers

Lodash tiene un _.pickBy la función que hace exactamente lo que estás buscando.

var thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

var result = _.pickBy(thing, function(value, key) {
  return _.startsWith(key, "a");
});

console.log(result.abc) // 6789
console.log(result.b)   // undefined
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
 193
Author: serg10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-31 06:48:16

Simplemente cambia el filtro a omitBy

 var result = _.omitBy(data, function(value, key) {
     return !key.startsWith("a");
 })
 27
Author: Krystian Jankowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-16 19:54:19

Aquí hay un ejemplo usando lodash 4.x:

var data = {
  "aaa":111,
  "abb":222,
  "bbb":333
};

var result = _.pickBy(data, function(value, key) {
  return key.startsWith("a");
});

console.log(result);
// Object {aaa: 111, abb: 222}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
<strong>Open your javascript console to see the output.</strong>
 13
Author: PaulMest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 22:57:57

Una forma no lodash de resolver esto de una manera bastante legible y eficiente:

function filterByKeys(obj, keys = []) {
  const filtered = {}
  keys.forEach(key => {
    if (obj.hasOwnProperty(key)) {
      filtered[key] = obj[key]
    }
  })
  return filtered
}

const myObject = {
  a: 1,
  b: 'bananas',
  d: null
}

filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
 0
Author: thomax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-24 07:25:35