在递归函数中构建嵌套对象数组

时间:2017-02-13 21:22:22

标签: javascript json recursion ecmascript-6

根据我专门针对React(React recursive tree pass JSON path)的原始问题,我意识到问题非常普遍。

我有一个递归函数,它基本上循环通过树状JSON结构,每次输出一个分支我想传递树中结构位置的对象,如下所示..是否有更简单的方法来传递结构?数据结构是否差/每个chid是否应附加唯一ID?

我的JSON对象位于下方,您可以看到我正在使用的内容。

非常感谢任何帮助!

1级儿童

{值:"水果"}

2级孩子

{value:" Fruit",nested_values:[{value:' Tropical'}}}

3级孩子

{value:" Fruit",nested_values:[{value:' Tropical',nested_values:[{value:' Pineapple' }]}]}

代码 - 有点工作,但后来我在同一个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>

1 个答案:

答案 0 :(得分:0)

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

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()