我有一个像...这样的对象
let object = {
person: {
pet: {
name: "Rover"
}
}
};
我想使用 lodash
(或任何与此相关的东西)来进行检查,例如...
Is the value at
object.person.pet.name
equal to"Spot"
?
目前我能看到的唯一选择是从对象中获取宠物名称,然后检查它是否等于“Spot”。
是否有一个函数可以用来进行一次检查,例如......
_.equals(object, 'person.pet.name', "Spot");
如果它通过 lodash
存在或不存在,那就太好了。
我目前使用 lodash
的原因是我不知道人、宠物或名字是否真的存在,因此 lodash 为我提供了一种“安全”获取该数据的方法。
最佳答案
lodash中似乎不存在这样的方法。
无论如何,您可以使用 findKey
方法来查找符合给定要求的 key 。
_.findKey(object, { 'person.pet.name' : 'Spot' });
如果它返回未定义
,则意味着它不相等。
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'
<小时/>
<小时/>
非loadash自定义函数
const object = {
person: {
pet: {
name: 'Rover',
},
},
};
function checkEquality(obj, key, value) {
const val = key.split('.')
.reduce((tmp, x) => (tmp !== void 0 && tmp[x] !== void 0 ? tmp[x] : void 0), obj);
if (val === void 0) return false;
return val === value;
}
console.log(checkEquality(object, 'person.pet.name', 'Rover'));
console.log(checkEquality(object, 'person.pet.name', 'RoverTT'));
console.log(checkEquality(object, 'person.petak.name', 'Rover'));
关于node.js - lodash 检查 object.path 是否等于值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55833471/