2016-07-25 55 views
1

我有以下對象數組:濾波對象陣列只包含主要使用Lodash

{ 
    running: false, 
    swimming: false, 
    drawing: true 
    } 

我想將對象陣列只有那些具有假性質進行篩選。從那裏我只想得到數組的關鍵字。

例如。

[running, swimming] 

我有通過下面的去除有真布爾值的第一部分:

var filtered = _.pick(hobbies, function(value, key) {return !value;}); 

什麼是「平坦」當前的陣列,這樣我只有有鑰匙的最佳方式值?

回答

3

的Lodash _.keys()功能提供正是你所問的:

var hobbies = { 
 
    running: false, 
 
    swimming: false, 
 
    drawing: true 
 
}; 
 

 
var filtered = _.keys(_.pick(hobbies, function(value) {return !value;})); 
 

 
console.log(filtered); 
 

 
// alternate approach using chain notation 
 
var keys = _ 
 
    .chain(hobbies) 
 
    .pick(v => !v) 
 
    .keys(); 
 

 
console.log(keys);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.js"></script>

注意,在Lodash 4.x中,_.pick()已發生變化,則應改用_.pickBy() aboce。

3

由於可以用純JavaScript,那麼我建議你使用Object.keysArray.prototype.filter

var obj = { 
 
    running: false, 
 
    swimming: false, 
 
    drawing: true 
 
}; 
 

 
var items = Object.keys(obj).filter(k => !obj[k]); 
 
console.log(JSON.stringify(items));