如何使用 lodash 在 Json 文件中的数组中仅获取具有特定属性的对象?
How to get only objects that have a certain atribute inside an array in a Json file using lodash?
代码笔:http://codepen.io/giorgiomartini/pen/jEvaxZ
我有这个Api:
http://private-5d90c-kevinhiller.apiary-mock.com/angular_challenge/horror_movies
像这样的结构:
如您所见,有一个 offers
数组,其中有一个 provider_id,例如,我只想获取提供商 2 中的电影。
{
"id": 140524,
"title": "Dracula Untold",
"poster": "https://images.justwatch.com/poster/298962/s332",
"full_path": "https://www.justwatch.com/us/movie/dracula-year-zero",
"object_type": "movie",
"original_release_year": 2014,
"offers": [
{
"monetization_type": "buy",
"provider_id": 2,
"retail_price": 14.99,
"currency": "USD",
"urls": {
"standard_web": "https://itunes.apple.com/us/movie/dracula-untold/id921386678?uo=4"
},
"presentation_type": "hd"
},
{
"monetization_type": "buy",
"provider_id": 2,
"retail_price": 14.99,
"currency": "USD",
"urls": {
"standard_web": "https://itunes.apple.com/us/movie/dracula-untold/id921386678?uo=4"
},
"presentation_type": "sd"
},
...
我怎样才能只获得带有 provider_id 2 的电影?使用 lodash ?
谢谢。
试试这个
var data = _.chain(data)
.map(function(el) {
el.offers = _.chain(el.offers)
.uniq('provider_id')
.filter(function(offer) {
return offer.provider_id === 2;
})
.value();
return el;
})
.filter(function(el) {
return el.offers && el.offers.length;
})
.value();
var all = yourArrayOfObjects;
var onlyWant = _.filter(yourArrayOfObjects, function(item) {
return _.any(item.offers, function(offer) {
return offer.provider_id === 2;
});
}
代码笔:http://codepen.io/giorgiomartini/pen/jEvaxZ
我有这个Api:
http://private-5d90c-kevinhiller.apiary-mock.com/angular_challenge/horror_movies
像这样的结构:
如您所见,有一个 offers
数组,其中有一个 provider_id,例如,我只想获取提供商 2 中的电影。
{
"id": 140524,
"title": "Dracula Untold",
"poster": "https://images.justwatch.com/poster/298962/s332",
"full_path": "https://www.justwatch.com/us/movie/dracula-year-zero",
"object_type": "movie",
"original_release_year": 2014,
"offers": [
{
"monetization_type": "buy",
"provider_id": 2,
"retail_price": 14.99,
"currency": "USD",
"urls": {
"standard_web": "https://itunes.apple.com/us/movie/dracula-untold/id921386678?uo=4"
},
"presentation_type": "hd"
},
{
"monetization_type": "buy",
"provider_id": 2,
"retail_price": 14.99,
"currency": "USD",
"urls": {
"standard_web": "https://itunes.apple.com/us/movie/dracula-untold/id921386678?uo=4"
},
"presentation_type": "sd"
},
...
我怎样才能只获得带有 provider_id 2 的电影?使用 lodash ?
谢谢。
试试这个
var data = _.chain(data)
.map(function(el) {
el.offers = _.chain(el.offers)
.uniq('provider_id')
.filter(function(offer) {
return offer.provider_id === 2;
})
.value();
return el;
})
.filter(function(el) {
return el.offers && el.offers.length;
})
.value();
var all = yourArrayOfObjects;
var onlyWant = _.filter(yourArrayOfObjects, function(item) {
return _.any(item.offers, function(offer) {
return offer.provider_id === 2;
});
}