javascript 使用 lodash/underscore.js 从数组中获取对象属性和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27816213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:01:52  来源:igfitidea点击:

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

javascriptarraysunderscore.jslodash

提问by RedGiant

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:

我想过滤掉最后一个对象并[{data-model_id:409},{data-model_id:384}]从前两个对象中提取。我试过这个代码:

 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?

它只返回一个值数组,["409", "384"]。是否有一个函数可以在 lodash 或下划线中返回整个对象?

回答by pawel

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

使用纯JS来展示逻辑:你需要把filter没有key的元素取出来,然后map新的集合到另一种形式:

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/

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

回答by Amit Joki

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

如果我告诉您仅使用本机 javascript 就可以做到这一点呢?只要使用Array.filterObject.keys,使用前进行筛选,后者拿到钥匙,然后返回一个Boolean通过比较的指标Array由归国Object.keys

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

回答by Alexander T.

In lodashyou can do like this:

lodash你可以这样做:

get full object

获取完整对象

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

get only data-model_idproperty

只得到data-model_id财产

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

Example

例子