我有一些json并希望返回一些嵌套对象,这是json:
{
"existingPackage": {
"primaryBundle": {
"id": "2031",
"serviceId": "114297251",
"name": "TV - Entertainment, Drama, Movies",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Drama",
"id": "104",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
},
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
}
]
}
}
}
目标是仅返回具有swappableProducts属性且具有特定id的productsarray中的项目。 因此,例如当我的productId = 105时,我想返回:
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
}
}
如何使用lodash返回此内容?
答案 0 :(得分:1)
这是我的方法:
_.filter(
products,
i => _.every([
_.has(i, 'swappableProducts'),
_.eq(_.result(i, 'id'), '105')
])
);
这个想法是将两个谓词都传递给every()。第一个使用has()来检查swappableProducts
属性是否存在。第二个谓词结合eq()和result()来检查id
值。
答案 1 :(得分:0)
你可以做这样的事情
_.filter(data.existingPackage.primaryBundle.products,
function(o) {
return o.swappableProducts !== undefined && o.id==="105";
});
答案 2 :(得分:0)
这是一个返回所需结果的函数
const getProducts = obj => obj.existingPackage.primaryBundle.products;
const withSwappable = _.curry((myId, obj) => _.result(obj, 'swappableProducts[0].id', false) == myId)
function getProductsWithId(data, myId) {
return _.filter(getProducts(data), withSwappable(myId))
}
const data = {
"existingPackage": {
"primaryBundle": {
"id": "2031",
"serviceId": "114297251",
"name": "TV - Entertainment, Drama, Movies",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Drama",
"id": "104",
"price": 2000,
"gifted": false,
"swappableProducts": [{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}]
},
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}]
}
]
}
}
}
console.log(getProductsWithId(data, "107"));
console.log(getProductsWithId(data, "100"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;