有没有办法通过仅提取某些值来减少嵌套的 json?
Is there a way to reduce a nested json by extracting only certain values?
我有以下嵌套的 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"]
有什么优雅的方法可以用 mapping/filter 函数实现这个吗?
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) );
我有以下嵌套的 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"]
有什么优雅的方法可以用 mapping/filter 函数实现这个吗?
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) );