在lodash中有更好的方法吗?我基本上试图找到所有具有空值的键。
var data = [
{ user: 'John', pos: null },
{ user: 'Tim', age: 40 },
{ user: 'Dave', age: null }
];
$scope.parsed = [];
_.each(data, function(obj) {
_.each(_.keys(obj), function(k){
if (obj[k] === null) {
$scope.parsed.push(k);
}
})
});
console.info($scope.parsed);
输出:[“pos”,“age”]
谢谢!
答案 0 :(得分:1)
试试这个
var data = [
{ user: 'John', pos: null },
{ user: 'Tim', age: 40 },
{ user: 'Dave', age: null }
];
var result = _(data)
.map(function (element) {
return _.keys(_.pick(element, _.isNull));
})
.flatten()
.value();
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
&#13;
答案 1 :(得分:0)
不确定如何定义'更好',但我认为这是一个更具功能性的答案 - 过滤那些值为null的元素
$scope.parsed = _.filter(data, function(d) {
return (_.values(d).indexOf(null) !== -1);
}
var data = [{
user: 'John',
pos: null
}, {
user: 'Tim',
age: 40
}, {
user: 'Dave',
age: null
}];
parsed = _.filter(data, function(d) {
return (_.values(d).indexOf(null) !== -1);
});
console.log(parsed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>