所以我有一个对象和数组。我想检查对象是否包含数组中的任何键。像这样:
对象:
const user = {
firstname: 'bob',
lastname: 'boblastname'
email: 'bob@example.com'
}
阵列:
const lastname = ['lastname'];
const userDetails = ['firstname', 'email'];
因此,在检查密钥存在时,它应该返回true。 例:
_.includesKey(user, lastname) // true
_.includesKey(user, userDetails ) // true
答案 0 :(得分:6)
我知道问题是关于lodash,但我一直想知道为什么你会使用第三方库来执行一项相当简单的任务
使用基本js工具解决问题的方法可能是
const user = {
firstname: 'bob',
lastname: 'boblastname',
email: 'bob@example.com'
}
const lastname = ['lastname'];
const userDetails = ['firstname', 'email'];
const hasLastName = lastname.every(prop => prop in user)
const hasDetails = userDetails.every(prop => prop in user)
console.log("has last name?", hasLastName)
console.log("has user details?", hasDetails)
它使你的项目变得更小,不会因为外部库而膨胀它,它肯定更快,我认为它更容易阅读和理解。
答案 1 :(得分:0)
您可以使用some
和intersection
并返回true / false作为结果。
const user = {
firstname: 'bob',
lastname: 'boblastname',
email: 'bob@example.com'
}
const lastname = ['lastname'];
const userDetails = ['firstname', 'email'];
console.log(_.some(_.intersection(lastname, _.keys(user))))
console.log(_.some(_.intersection(userDetails, _.keys(user))))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>