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
Get object properties and values from array using lodash/underscore.js
提问by RedGiant
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 filter
out the elements that don't have the key, then map
the 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'] }
});
回答by Amit Joki
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
如果我告诉您仅使用本机 javascript 就可以做到这一点呢?只要使用Array.filter
和Object.keys
,使用前进行筛选,后者拿到钥匙,然后返回一个Boolean
通过比较的指标Array
由归国Object.keys
var k = array.filter(function(obj){
return Object.keys(obj).indexOf("data-model_id") > -1;
});