Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 递归遍历数组转成对应树形数组结构 #36

Open
lizheng0515 opened this issue Jul 29, 2021 · 0 comments
Open

js 递归遍历数组转成对应树形数组结构 #36

lizheng0515 opened this issue Jul 29, 2021 · 0 comments
Labels
JavaScript This doesn't seem right

Comments

@lizheng0515
Copy link
Owner

lizheng0515 commented Jul 29, 2021

> 将entries 按照 level 转换成 result 数据结构

const entries = [
    {
        "province": "浙江", "city": "杭州", "name": "西湖"
    }, {
        "province": "四川", "city": "成都", "name": "锦里"
    }, {
        "province": "四川", "city": "成都", "name": "方所"
    }, {
        "province": "四川", "city": "阿坝", "name": "九寨沟"
    }
];
	
const level = ["province", "city", "name"];

const  result = [
	{
		value:'浙江'
		children:[
			{
				value:'杭州',
				children:[
					{
						value:'西湖'
					}
				]
			}
		]
	},
	{
		value:'四川'
		children:[
			{
				value:'成都',
				children:[
					{
						value:'锦里'
					},
					{
						value:'方所'
					}
				]
			},
			{
				value:'阿坝',
				children:[
					{
						value:'九寨沟'
					}
				]
			}
		]
	},
]

思路: 涉及到树形数组,采用递归遍历的方式

function transfrom(list, level) {
  const res = [];
  list.forEach(item => {
    pushItem(res, item, 0);
  });

  function pushItem(arr, obj, i) {
    const o = {
      value: obj[level[i]],
      children: [],
    };
    // 判断传入数组里是否有value等于要传入的项
    const hasItem = arr.find(el => el.value === obj[level[i]]);
    let nowArr;
    if(hasItem) {
      // 存在,则下一次遍历传入存在项的children
      nowArr = hasItem.children;
    }else{
      // 不存在 压入arr,下一次遍历传入此项的children
      arr.push(o);
      nowArr = o.children;
    }
    if(i === level.length - 1) delete o.children;
    i++;
    if(i < level.length) {
      // 递归进行层级的遍历
      pushItem(nowArr, obj, i);
    }
  }
}

transfrom(entries, level);
@lizheng0515 lizheng0515 added the JavaScript This doesn't seem right label Jul 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript This doesn't seem right
Projects
None yet
Development

No branches or pull requests

1 participant