How to filter keys of an object with lodash?

落花浮王杯 提交于 2019-11-26 12:06:01

问题


I have an object with some keys, and I want to only keep some of the keys with their value?

I tried with filter:

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

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

console.log(result);

But it prints an array:

[111, 222]

Which is not what I want.

How to do it with lodash? Or something else if lodash is not working?

Live demo: http://jsbin.com/moqufevigo/1/edit?js,output


回答1:


Lodash has a _.pickBy function which does exactly what you're looking for.

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>



回答2:


Just change filter to omitBy

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



回答3:


Here is an example using 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>



回答4:


A non-lodash way to solve this in a fairly readable and efficient manner:

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}


来源:https://stackoverflow.com/questions/30726830/how-to-filter-keys-of-an-object-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!