gpt4 book ai didi

javascript - lodash 扁平化 JSON 并显示原始路径

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:26 24 4
gpt4 key购买 nike

我有一个带有嵌套子项的 JSON 对象,我想使用 lodash 对其进行展平和修改。理想情况下,修改后的 JSON 将具有嵌套子项所在的原始级别的值,并显示其原始路径。

这是示例 JSON:

var data = [
{id: 0, name: 'Australia', children: [
{id: 10, name: 'Melbourne', children: []},
{id: 11, name: 'Sydney', children: [
{id: 100, name: 'Surry Hills', children: []},
{id: 102, name: 'Darlinghurst', children: []}
]},
{id: 13, name: 'Kambalda', children: []}
]},
{id: 1, name: 'Spain', children: [
{id: 20, name: 'Barcelona', children: []},
{id: 21, name: 'Madrid', children: []}
]},
{id: 3, name: 'UK', children: [
{id: 30, name: 'London', children: [
{id: 302, name: 'Knightsbridge', children: []},
{id: 309, name: 'West End', children: []}
]},
{id: 33, name: 'Leeds', children: []},
{id: 35, name: 'Manchester', children: []}
]}
];

我想生成的转换后的 JSON 是:

 [
{id: 0, name: 'Australia', level: 0, pathname: 'Australia'},
{id: 10, name: 'Melbourne', level: 1, pathname: 'Australia > Melbourne'},
{id: 11, name: 'Sydney', level: 1, pathname: 'Australia > Sydney'},
{id: 100, name: 'Surry Hills', level: 2, pathname: 'Australia > Sydney > Surry Hills'},
{id: 102, name: 'Darlinghurst', level: 2, pathname: 'Australia > Sydney > Darlinghurst'},
{id: 13, name: 'Kambalda', level: 1, pathname: 'Australia > Kambalda'},
{id: 1, name: 'Spain', level: 0, pathname: 'Spain'},
{id: 20, name: 'Barcelona', level: 1, pathname: 'Spain > Barcelona'},
{id: 21, name: 'Madrid', level: 1, pathname: 'Spain > Madrid'},
{id: 3, name: 'UK', level: 0, pathname: 'UK'},
{id: 30, name: 'London', level: 1, pathname: 'UK > London'},
{id: 302, name: 'Knightsbridge', level: 2, pathname: 'UK > London > Knightsbridge'},
{id: 309, name: 'West End', level: 2, pathname: 'UK > London > West End'},
{id: 33, name: 'Leeds', level: 1, pathname: 'UK > Leeds'},
{id: 35, name: 'Manchester', level: 1, pathname: 'UK > Manchester'}
]

我一直在玩 _.chain、_.flatten 和 _.pluck,但无法接近任何东西。

最佳答案

您可以使用一个简单的递归辅助函数来生成一个数组数组,然后使用 _.flattenDeep 来展平它。这做你想要的:

function flattenMyTree(tree) {
function recurse(nodes, path) {
return _.map(nodes, function(node) {
var newPath = _.union(path, [node.name]);
return [
_.assign({pathname: newPath.join(' > '), level: path.length}, _.omit(node, 'children')),
recurse(node.children, newPath)
];
});
}
return _.flattenDeep(recurse(tree, []));
}

关于javascript - lodash 扁平化 JSON 并显示原始路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com