如何用lodash过滤对象的键?

2020/10/20 06:01 · javascript ·  · 0评论

我有一个带有一些键的对象,我只想保留一些键的值?

我尝试了filter

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

const result = _.filter(data, (value, key) => key.startsWith("a"));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

但是它会打印一个数组:

[111,222]

这不是我想要的。

用lodash怎么做?如果lodash无法正常工作,还是有其他原因?

Lodash的_.pickBy功能完全可以满足您的需求。

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>

只要改变滤波器omitBy

const data = { aaa: 111, abb: 222, bbb: 333 };
const result = _.omitBy(data, (value, key) => !key.startsWith("a"));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

这是使用lodash4.x的示例

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

const result = _.pickBy(data, (value, key) => key.startsWith("a"));

console.log(result);
// Object { aaa: 111, abb: 222 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<strong>Open your javascript console to see the output.</strong>

一种非易用的方式,以一种相当可读和有效的方式解决此问题:

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
}

const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
console.log(result)
本文地址:http://javascript.askforanswer.com/ruheyonglodashguolvduixiangdejian.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!