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

如何在Javascript中映射所有叶节点的值?,javascript,tree,Javascript,Tree,我有一个嵌套的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,"Wor

我有一个嵌套的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"}]
预期输出是这样的

我的示例的预期输出:

所以我想映射叶节点的值。在本例中,世界城市。国家,世界城市。人口和世界城市。城市仅为每个儿童对象的名称和值

目前这是我拥有的功能:

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

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

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

常数a={ 儿童:[ { 姓名:阿富汗, 儿童:[ { 世界城市。国家:阿富汗, 世界城市。人口:2997, 世界城市。城市:Qal eh ye Now }, { 世界城市。国家:阿富汗, 世界城市。人口:7407, 世界城市。城市:马哈茂德-埃拉齐 }, { 世界城市。国家:阿富汗, 世界城市。人口:10000, 世界城市。城市:塔林科特 } ] } ] }; const deep=x=>{ 如果Array.isArrayx.children{ x、 children=x.children.mapreep; 返回x; }否则{ 返回{ 名称:x[世界城市.城市], 价值:x[世界城市.人口] }; } }; 常数b=深度a;
console.logb;您能定义输出对象吗?另外,您的JSON格式不正确。@anandudaviadone@thefourtheye我把它缩短了。它更具可读性now@SyedAriff仍然不清楚,您能否提供您提供的示例的示例输出国家/地区和aCity是硬编码。有没有一种方法可以避免在我的源代码中出现这种情况,同时获得相同的结果?基本上将JSON树的叶节点映射到名称和值。啊,我想我现在明白你的意思了。如果我错了,请纠正我:您希望深入,直到子项键没有更多的子项键,然后将它们映射到名称和值,对吗?@SyedAriff更新了答案。
{"children":[{"name":"Afghanistan","children":[{"name":"Qal eh-ye Now","value":2997}]]}
var mappedData = nestedData.children.map(function (d) {
                      return { name: d[groupKey], value: d[sizeKey] };
                  }); //groupKey is World.Cities.City ,sizeKey is Population