javascript - 有没有办法通过只提取某些值来减少嵌套的 json?
问题描述
我有以下嵌套的 json 结构:
{
element: "a",
items: ["l1", "l2"],
children: [{
element: "b",
children: [{
element: "c",
items: ["l3"]
}, {
element: "b",
child: {
element: "c",
items: ["l4"]
}
}
基本上:
- 一个“元素”包含一个名称、一个项目列表和一个子元素列表,这些子元素本身就是一个“元素”
- 项目列表可能会丢失
我想处理这个 json 以获得一个包含所有项目的平面数组:
const finalArray = parse(json); //returns ["l1","l2","l3","l4"]
有没有什么优雅的方法可以通过映射/过滤功能来实现这一点?
解决方案
const getItems = (acc = [], { items = [], child = {}, children = [] }) =>
[
...acc,
...items,
...(child?.items || []),
...(children.length ? children.reduce(getItems, acc) : [])
];
const data = {
element:"a",
items: ["l1","l2"],
children: [
{
element: "b",
children: [
{ element: "c", items: ["l3"] },
{ element: "b", child: { element: "c", items: ["l4"] } }
]
}
]
}
console.log( getItems([], data) );
推荐阅读
- azure - 使用 fluent API 跟踪异步 Azure 操作
- javascript - 跨浏览器 javascript window.open 方法
- android-studio - Android Studio 和构建它的 IntelliJ 平台之间有什么主要区别吗?
- rest - WooCommerce REST API“woocommerce_rest_cannot_view”
- wordpress - 如何使用 .htaccess RewriteRule 将下划线更改为连字符
- python - 重新模块的一些问题(特别是:字符类中的 .(DOT) )
- javascript - 月份为 1 位或 2 位数字的日期的正则表达式
- javafx - JavaFX,可编辑的 DatePicker 未在日期中添加分隔符
- javascript - Vue - 在组件或路由视图中使用 axios?
- python - 确定未排序列表(集)的评估措施