【问题标题】:Build nested object arrays within recursive function在递归函数中构建嵌套对象数组
【发布时间】:2017-07-02 00:19:58
【问题描述】:

根据我最初专门针对 React (React recursive tree pass JSON path) 提出的问题,我意识到这个问题非常普遍。

我有一个递归函数,它本质上循环遍历树状 JSON 结构,每次它输出一个分支时,我想传递树中结构位置的对象,如下所示。有没有更简单的方法来传递结构?数据结构是否糟糕/每个孩子都应该附加一个唯一的 ID 吗?

我的 JSON 对象在下面,因此您可以看到我正在处理的内容。

非常感谢任何帮助!

1 级孩子

{值:“水果”}

2 级孩子

{value: "水果", nested_values: [{ value: 'Tropical'}] }

3 级孩子

{value: "水果", nested_values: [{ value: '热带', nested_values:[{ value: '菠萝' }]}] }

代码 - 有点工作,但我在同一个 nested_values 数组中获取所有值

 const createSelectionHierarchy = (data, isSub, level = 2, hierarchy = {}) => {
        let children = [];
        if (isSub) { level++; }
        let obj = {};
        obj.name = cat;

        const cat = hierarchy.value;    

        for (let i in data) {

            const subcat = data[i].value;

            if (typeof(data[i].nested_values) === 'object') { // Sub array found, build structure
                obj.values = subcat;
                obj.nested_values = [];

                hierarchy.nested_values.push(obj);

                children.push(
                    <FilterItem key={i} data={data[i]} hierarchy={hierarchy} level={level}>
                        {createSelectionHierarchy(data[i].nested_values, true, level, hierarchy)}
                    </FilterItem>
                );
            } else { // No sub array, bottom of current branch
                children.push(
                    <p className="filter-item level-last" key={i}>
                        {data[i].value}
                    </p>);
            }
        }
        return children;
    }

JSON

{
        "value": "Fruit",
        "occurrence_count": 5,
        "nested_values": [{
            "value": "Berries",
            "occurrence_count": 3,
            "nested_values": [{
                "value": "Strawberry",
                "occurrence_count": 1
            }, {
                "value": "Blackberry",
                "occurrence_count": 1
            }, {
                "value": "Raspberry",
                "occurrence_count": 1
            }, {
                "value": "Redcurrant",
                "occurrence_count": 1
            }, {
                "value": "Blackcurrant",
                "occurrence_count": 1
            }, {
                "value": "Gooseberry",
                "occurrence_count": 1
            }, {
                "value": "Cranberry",
                "occurrence_count": 1
            }, {
                "value": "Whitecurrant",
                "occurrence_count": 1
            }, {
                "value": "Loganberry",
                "occurrence_count": 1
            }, {
                "value": "Strawberry",
                "occurrence_count": 1
            }]
        }, {
            "value": "Tropical",
            "occurrence_count": 2,
            "nested_values": [{
                "value": "Pineapple",
                "occurrence_count": 1
            }, {
                "value": "Mango",
                "occurrence_count": 1
            }, {
                "value": "Guava",
                "occurrence_count": 1
            }, {
                "value": "Passion Fruit",
                "occurrence_count": 1
            }, {
                "value": "Dragon Fruit",
                "occurrence_count": 1
            }]
        }]
}

期望的输出

<FilterItem ...... hierarchy={{value: "Fruit"}}>
    <FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical'}] }}>
        <FilterItem ...... hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical', nested_values:[{ value: 'Pineapple' }]}] }}>
        </FilterItem>
    </FilterItem>
</FilterItem>

【问题讨论】:

  • @r1verside - 你有例子吗?
  • @ibrahimmahrir - 我更新了我的答案
  • 你有 JavaScript(意思是 ECMA 脚本)版本的代码吗?
  • @Traktor53 - 不幸的是不是,但上面的内容很容易破译吗?它只是一个函数,唯一奇怪的是我将 JSX 元素推入数组而不是对象
  • @Zinc 请看一下我的回答,看看您是否想要。如果有,我会添加解释。

标签: javascript json recursion ecmascript-6


【解决方案1】:

对于每个分支(树的级别),此函数将提取值,然后在其每个子节点(如果有)上调用自身,并将其返回值存储在数组中。

function convert(branch) {  
  const hierarchy = {
    value: branch.value
  };
  if (branch.nested_values !== undefined)
    hierarchy.nested_values = branch.nested_values.map(subranch => convert(subranch))
  return hierarchy;
}

const input = {
  "value": "Fruit",
  "occurrence_count": 5,
  "nested_values": [{
    "value": "Berries",
    "occurrence_count": 3,
    "nested_values": [{
      "value": "Strawberry",
      "occurrence_count": 1
    }, {
      "value": "Blackberry",
      "occurrence_count": 1
    }, {
      "value": "Raspberry",
      "occurrence_count": 1
    }, {
      "value": "Redcurrant",
      "occurrence_count": 1
    }, {
      "value": "Blackcurrant",
      "occurrence_count": 1
    }, {
      "value": "Gooseberry",
      "occurrence_count": 1
    }, {
      "value": "Cranberry",
      "occurrence_count": 1
    }, {
      "value": "Whitecurrant",
      "occurrence_count": 1
    }, {
      "value": "Loganberry",
      "occurrence_count": 1
    }, {
      "value": "Strawberry",
      "occurrence_count": 1
    }]
  }, {
    "value": "Tropical",
    "occurrence_count": 2,
    "nested_values": [{
      "value": "Pineapple",
      "occurrence_count": 1
    }, {
      "value": "Mango",
      "occurrence_count": 1
    }, {
      "value": "Guava",
      "occurrence_count": 1
    }, {
      "value": "Passion Fruit",
      "occurrence_count": 1
    }, {
      "value": "Dragon Fruit",
      "occurrence_count": 1
    }]
  }]
};

function convert(branch) {
  const hierarchy = {
    value: branch.value
  };
  if (branch.nested_values !== undefined)
    hierarchy.nested_values = branch.nested_values.map(subranch => convert(subranch))
  return hierarchy;
}

console.log(convert(input));

附带说明,您提供的不是有效的 JSON(键不能有引号),它是一个 JavaScript 对象。要从 JSON 字符串中获取对象,您必须调用 JSON.parse()

【讨论】:

  • 谢谢你,但我认为你对我的问题的理解太过分了,我只是在寻找层次结构对象,以便在每次迭代时将新的数组结构推入其中。即hierarchy={{value: "Fruit"}},然后hierarchy={{value: "Fruit", nested_values: [{ value: 'Tropical'}] }} 等
  • 我想我做到了。您所追求的更简单 - 请参阅编辑。
  • 酷,我将如何将它应用到我上面的递归函数中?
猜你喜欢
  • 1970-01-01
  • 2015-04-11
  • 2014-07-17
  • 2019-02-08
  • 1970-01-01
  • 2019-11-23
  • 2021-01-23
  • 2016-07-12
  • 1970-01-01
相关资源
最近更新 更多