javascript - 具有条件的嵌套数组的减速器函数
问题描述
我正在努力为我拥有的嵌套对象编写一个 reducer 函数。
{
"queryResult": [{
"__typename": "Parent",
"_id": "ABC",
"items": [{
"__typename": "Child",
"_id": "123",
"subitems": [{
"__typename": "Grandchild",
"_id": "abc",
}, {
"__typename": "Grandchild",
"_id": "def",
}, {
"__typename": "Grandchild",
"_id": "ghi",
}, {
"__typename": "Grandchild",
"_id": "jkl",
}, {
"__typename": "Grandchild",
"_id": "mno",
}, {
"__typename": "Grandchild",
"_id": "pqr",
}]
}, {
"__typename": "Child",
"_id": "456",
"subitems": [{
"__typename": "Grandchild",
"_id": "aaa",
}, {
"__typename": "Grandchild",
"_id": "bbb",
}, {
"__typename": "Grandchild",
"_id": "ccc",
}, {
"__typename": "Grandchild",
"_id": "ddd",
}]
}, {
"__typename": "Child",
"_id": "789",
"subitems": [{
"__typename": "Grandchild",
"_id": "eee",
}]
}]
}]
}
queryResult
可以有很多Parent
s。每个Parent
人都有item
s,每个item
人都有subitem
s 和他们.id
的 s。
如何编写一个reducer,queryResult
通过接收parentId
和itemId
返回s的数组来减少subitem
s?例如,对于parentId
=ABC
和itemId
=456
我需要如下所示的结果:
"subitems": [{
"__typename": "Grandchild",
"_id": "aaa",
}, {
"__typename": "Grandchild",
"_id": "bbb",
}, {
"__typename": "Grandchild",
"_id": "ccc",
}, {
"__typename": "Grandchild",
"_id": "ddd",
}]
注意:所有的 ID 都是随机的,没有任何逻辑。
解决方案
const sample = {
"queryResult": [{
"__typename": "Parent",
"_id": "ABC",
"items": [{
"__typename": "Child",
"_id": "123",
"subitems": [{
"__typename": "Grandchild",
"_id": "abc",
}, {
"__typename": "Grandchild",
"_id": "def",
}, {
"__typename": "Grandchild",
"_id": "ghi",
}, {
"__typename": "Grandchild",
"_id": "jkl",
}, {
"__typename": "Grandchild",
"_id": "mno",
}, {
"__typename": "Grandchild",
"_id": "pqr",
}]
}, {
"__typename": "Child",
"_id": "456",
"subitems": [{
"__typename": "Grandchild",
"_id": "aaa",
}, {
"__typename": "Grandchild",
"_id": "bbb",
}, {
"__typename": "Grandchild",
"_id": "ccc",
}, {
"__typename": "Grandchild",
"_id": "ddd",
}]
}, {
"__typename": "Child",
"_id": "789",
"subitems": [{
"__typename": "Grandchild",
"_id": "eee",
}]
}]
}]
};
function getSubItemsByParentAndItemId(arr, parentId, itemId) {
return ((arr.find(parentItem =>
parentItem.__typename === 'Parent'
&& parentItem._id === parentId
) || { items: [] }).items.find(childItem =>
childItem.__typename === 'Child'
&& childItem._id === itemId
) || { subitems: [] }).subitems;
}
console.log(
getSubItemsByParentAndItemId(sample.queryResult, 'ABC', '456')
);
console.log(
getSubItemsByParentAndItemId(sample.queryResult, 'XYZ')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
推荐阅读
- python - 如何使用 Google Datastore 从查询中找到总实体
- encryption - 用作标识符时如何散列社会安全号码
- javascript - 为什么我们需要将 DerivedObject.prototype.constructor 设置为 DerivedObject?
- python - 如何使用 urllib 读取 txt.file
- c - 如何传递没有静态顺序的数组?C语言
- javascript - 在向 flickr.photos.search API 发出 ajax 获取请求后获取和显示数据后,src 属性未定义
- python - Django migrate 尝试连接到非默认数据库
- python-3.x - 来自代理后面的 pytrends
- javascript - addEventListener 指向作为对象属性的函数,加载时不触发函数
- sonarqube - 来自 create-react-app 测试的 SonarCloud 覆盖率报告