Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  88] [ 2]  / answers: 1 / hits: 19761  / 10 Years ago, wed, january 7, 2015, 12:00:00

Fiddle Example



I have an array like this:



var array = [ { 
'data-price': '0.00',
'data-term': '532',
'data-model_id': '409',
},
{
'data-price': '0.00',
'data-term': '483',
'data-model_id': '384',
},
{ text: 'dffdfddgfdgf' } ];


I want to filter out the last object and extract [{data-model_id:409},{data-model_id:384}] from the first two objects. I have tried this code:



 var k = _(array).filter('data-model_id').pluck('data-model_id').value();
console.log(k);


and it returns an array of the values only, [409, 384] . Is there a function to return the whole objects in lodash or underscore?


More From » arrays

 Answers
8

Using plain JS to show the logic: you need to filter out the elements that don't have the key, then map the new collection to another form:



array.filter( function(item){
return 'data-model_id' in item;
}).map( function( item ){
return { 'data-model_id' : item['data-model_id'] }
});


http://jsfiddle.net/dn4tn6xv/7/


[#68290] Saturday, January 3, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;