RedGiant
RedGiant

Reputation: 4748

Get object properties and values from array using lodash/underscore.js

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?

Upvotes: 1

Views: 19730

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77482

In lodash you can do like this:

get full object

console.log(_.filter(array, 'data-model_id'));

get only data-model_id property

var res = _.chain(array).filter('data-model_id').map(function (el) {
  return _.pick(el, 'data-model_id');
}).value();

Example

Upvotes: 2

pawel
pawel

Reputation: 36965

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/

Upvotes: 4

Amit Joki
Amit Joki

Reputation: 59232

What if I told you this is possible using just native javascript? Just use Array.filter and Object.keys, using the former to filter and the latter to get the keys and then returning a Boolean by comparing the index of the Array returned by Object.keys

var k = array.filter(function(obj){
   return Object.keys(obj).indexOf("data-model_id") > -1;
});

Upvotes: 3

Related Questions