1

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?

3 Answers 3

4

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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;
});

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.