在属性列表中,检查对象具有哪些 属性?对象只能具有其中一个属性
Of a list of properties, check which property an object has? Object can only have one of the properties
一个对象可以有 属性 a、b、c 或 d。
找出它有哪一个的最好方法是什么?
var input = {
name: 'Bob',
a: 1
}
预期输出:
a
我之前使用的是:
_.keys(_.pick(input, 'a', 'b', 'c', 'd'))[0]
但是想知道是否有更好的方法来做到这一点?
这应该可以做到。不确定它是否 "better" 但它会让你不必使用另一个库而且应该更轻一些。
var input = {
a: 1
}
function whichProperty(obj) {
var possibilities = ['a', 'b', 'c', 'd'];
return possibilities.filter(function (a) {
return obj[a];
})[0];
}
document.write(whichProperty(input));
不确定这是否更好,但也许表现力更强:
var result = _.find('abcd', function(key){
return _.has(input,key);
})
一个对象可以有 属性 a、b、c 或 d。
找出它有哪一个的最好方法是什么?
var input = {
name: 'Bob',
a: 1
}
预期输出:
a
我之前使用的是:
_.keys(_.pick(input, 'a', 'b', 'c', 'd'))[0]
但是想知道是否有更好的方法来做到这一点?
这应该可以做到。不确定它是否 "better" 但它会让你不必使用另一个库而且应该更轻一些。
var input = {
a: 1
}
function whichProperty(obj) {
var possibilities = ['a', 'b', 'c', 'd'];
return possibilities.filter(function (a) {
return obj[a];
})[0];
}
document.write(whichProperty(input));
不确定这是否更好,但也许表现力更强:
var result = _.find('abcd', function(key){
return _.has(input,key);
})