`
sillycat
  • 浏览: 2551983 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree

 
阅读更多
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree

Build Array Tree with Lodash
const _ = require('lodash');

const arr = [{
  "id": 1,
  "parentID": 0,
  "name": "carl"
},{
  "id": 2,
  "parentID": 1,
  "name": "kiko"
},{
  "id": 3,
  "parentID": 1,
  "name": "yuchen"
},{
  "id": 4,
  "parentID": 2,
  "name": "hello"
}];
const mainKey = "id";
const parentKey = "parentID";
const a = _.keyBy(arr, mainKey);
const result = _
         .chain(arr)
         .groupBy(parentKey)
         .forEach(function(v,k){
           k!='0' && (a[k].children=(a[k].children||[]).concat(v));
         })
         .result('0')
         .value();
console.log(JSON.stringify(result));

Convert Array to Hashmap
const _ = require('lodash');

const arr = [{
  "id": 1,
  "parentID": 0,
  "name": "carl"
},{
  "id": 2,
  "parentID": 1,
  "name": "kiko"
},{
  "id": 3,
  "parentID": 1,
  "name": "yuchen"
},{
  "id": 4,
  "parentID": 2,
  "name": "hello"
},{
  "id": 5,
  "parentID": 0,
  "name": "fly"
}];
const map = _.keyBy(arr, 'id');
console.log(JSON.stringify(map));

Find all Parents in Array
const _ = require('lodash');

const arr = [{
  "id": 1,
  "parentID": 0,
  "name": "carl"
},{
  "id": 2,
  "parentID": 1,
  "name": "kiko"
},{
  "id": 3,
  "parentID": 1,
  "name": "yuchen"
},{
  "id": 4,
  "parentID": 2,
  "name": "hello"
},{
  "id": 5,
  "parentID": 0,
  "name": "fly"
}];
const map = _.keyBy(arr, 'id');
console.log(JSON.stringify(map));

function findAncestors (nodeID) {
   let ancestors = [];
   let parentID = map[nodeID] && map[nodeID].parentID + "";
   ancestors.unshift(nodeID);
   while(parentID !== undefined && parentID !== "0") {
     ancestors.unshift(parentID)
     parentID = map[parentID] && map[parentID].parentID + "";
   }
   return ancestors;
}

const parents = findAncestors("4");
console.log(JSON.stringify(parents));


References:
https://danmartensen.svbtle.com/converting-a-tree-to-a-list-in-javascript
https://blog.wax-o.com/2014/01/how-to-find-deep-and-get-parent-in-javascript-nested-objects-with-recursive-functions-and-the-reference-concept-level-beginner/
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics