使用lodash在对象中查找属性的部分名称

时间:2017-04-28 18:46:58

标签: javascript lodash

我有一个看起来像这样的对象:

var user = {
 "user_number12": "1234",
 "user_number14": "1235",
 "email": "joe@yahoo.com"
}

我想通过搜索属性字符串找到所有用户" user_number"用lodash。

_.has(_.includes(user, "user_number"))

不起作用。我只是想知道如何将_.ha_.includes

连在一起

1 个答案:

答案 0 :(得分:2)

您可以使用_.pickBy。它返回一个对象,其中包含谓词为其返回truthy值的所有属性。您可以在谓词中使用_.includes()

var user = {
 "user_number12": "1234",
 "user_number14": "1235",
 "email": "joe@yahoo.com"
}
var newUser = _.pickBy(user, (value, key) => _.includes(key, "user_number"))
console.log(newUser);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>