2016-02-09 73 views
2

有沒有一種方法,我可以在陣列上進行篩選,但省略某些關鍵:使用值lodash?例如:Lodash過濾器和省略

var people = [{ 
    _id: 0, 
    name: 'Joe', 
    type: 1 
}, { 
    _id: 1, 
    name: 'James', 
    type: 2 
}, { 
    _id: 2, 
    name: 'Mary', 
    type: 0 
}, { 
    _id: 3, 
    name: 'Clark', 
    type: 0 
}]; 

var people_with_type_0 = _.filter(people, { 'type': 0 }); 

// so people_with_type_0 now contains the following 
var people_with_type_0 = [{ 
    _id: 2, 
    name: 'Mary', 
    type: 0 
}, { 
    _id: 3, 
    name: 'Clark', 
    type: 0 
}]; 

以上是輝煌的,但我想省略類型?

+0

瀏覽器支持?標記爲Node.js的... – MindVox

回答

1

people_with_type_0可以通過_.map()來獲得無 '類型' 屬性的對象:

var array = _.map(people_with_type_0, function(person) { 
    return _.omit(person, 'type'); 
}); 
console.log(array); 

此打印:

[ 
    { _id: 2, name: 'Mary' }, 
    { _id: 3, name: 'Clark' } 
] 
+0

你有這樣的一個答案http://stackoverflow.com/questions/35496966/mysql-like-query-result-using-loadsh-from-json-array –

3
_.map(_.filter(people,{type : 0}),_.partial(_.omit,_,'type')) 
2

我會用鏈式調用這樣的事情。使用filter()得到你需要的東西,然後map()改造的結果。

_(people) 
    .filter({ type: 0 }) 
    .map(_.unary(_.partialRight(_.omit, 'type'))) 
    .value();