简体   繁体   中英

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?

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM