gpt4 book ai didi

javascript - 如何在Javascript中映射所有叶节点的值?

转载 作者:行者123 更新时间:2023-12-03 01:12:23 24 4
gpt4 key购买 nike

我有一个像这样的嵌套 JSON 对象树:

{"children":[{"name":"Afghanistan","children":[{"World 
Cities.Country":"Afghanistan","World Cities.Population":2997,"World
Cities.City":"Qal eh-ye Now"},{"World Cities.Country":"Afghanistan","World
Cities.Population":7407,"World Cities.City":"Mahmud-E Eraqi"},{"World
Cities.Country":"Afghanistan","World Cities.Population":10000,"World
Cities.City":"Tarin Kowt"}]

预期输出像这样

{
"name": "flare",
"children": [
{
"name": "LEGISLATIVE",
"children": [
{
"name": "Legislative Branch",
"size": 20891
}
]
},
{
"name": "JUDICIAL",
"children": [
{
"name": "Supreme Court Law Library",
"size": 1589.3
},
{
"name": "New Mexico Compilation Commission",
"size": 1853.5
},
{
"name": "Judicial Standards Commission",
"size": 860.8
},
{
"name": "Court of Appeals",
"size": 5960.2
},
{
"name": "Supreme Court",
"size": 3421.1
},
{
"name": "Supreme Court Building Commission",
"size": 977.4
},
{
"name": "Administrative Office of the Courts",
"size": 65870.4
},
{
"name": "First Judicial District Court",
"size": 8372.5
},
{
"name": "Second Judicial District Court",
"size": 28154.6
},
{
"name": "Third Judicial District Court",
"size": 7808.3
},
{
"name": "Fourth Judicial District Court",
"size": 2577.2
},
{
"name": "Fifth Judicial District Court",
"size": 7389.5
},
{
"name": "Sixth Judicial District Court",
"size": 3630.7
},
{
"name": "Seventh Judicial District Court",
"size": 2895
},

我的示例的预期输出:

{"children":[{"name":"Afghanistan","children":[{"name":"Qal eh-ye Now","value":2997}]]}

所以我想映射叶节点的值。在此示例中,World Cities.Country、World Cities.Population 和 World Cities.City 只是每个子对象的名称和值。

目前这是我拥有的功能:

var mappedData = nestedData.children.map(function (d) {
return { name: d[groupKey], value: d[sizeKey] };
}); //groupKey is World.Cities.City ,sizeKey is Population

但显然这种语法不起作用,因为我首先需要访问这棵树的所有叶节点,然后对其应用映射函数。我怎样才能做到这一点?

最佳答案

这是实现这一目标的方法:

    const a = {
children: [
{
name: "Afghanistan",
children: [
{
"World Cities.Country": "Afghanistan",
"World Cities.Population": 2997,
"World Cities.City": "Qal eh-ye Now"
},
{
"World Cities.Country": "Afghanistan",
"World Cities.Population": 7407,
"World Cities.City": "Mahmud-E Eraqi"
},
{
"World Cities.Country": "Afghanistan",
"World Cities.Population": 10000,
"World Cities.City": "Tarin Kowt"
}
]
}
]
};

const deep = x => {
if (Array.isArray(x.children)) {
x.children = x.children.map(deep);
return x;
} else {
return {
name: x["World Cities.City"],
value: x["World Cities.Population"]
};
}
};

const b = deep(a);

console.log(b);

关于javascript - 如何在Javascript中映射所有叶节点的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52162108/

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