JavaScriptでJSONからツリー配列を構築する
JavaScriptに次の配列があるとします-
const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }];
そのような配列を1つ取り込むJavaScript関数を作成する必要があります。関数は、オブジェクトの「name」プロパティに基づいて、この配列からツリー構造を構築する必要があります。
したがって、上記の配列の場合、出力は次のようになります-
const output = [{ "code": "2", "name": "PENDING", "children": [{ "code": "2.2", "name": "PENDING CHILDREN", "children": [{ "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }] }] }, { "code": "1", "name": "ACTIVE", "children": [{ "code": "1.1", "name": "ACTIVE CHILDREN", "children": [{ "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }] }] }];
例
このためのコードは-
になりますconst arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }]; const transformToTree = (arr, root = '') => { let map = {}, last = [root], level = 0; map[root] = {}; arr.forEach(el => { let parent = root; while (level && last[level].length >= el.code.length) { level--; }; parent = last[level]; level++; last.length = level; last.push(el.code); map[el.code] = el; map[parent].children = map[parent].children || []; map[parent].children.push(el); }); return map[root].children; }; console.log(JSON.stringify(transformToTree(arr), undefined, 4));
出力
そして、コンソールの出力は-
になります[ { "code": "2", "name": "PENDING", "children": [ { "code": "2.2", "name": "PENDING CHILDREN", "children": [ { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" } ] } ] }, { "code": "1", "name": "ACTIVE", "children": [ { "code": "1.1", "name": "ACTIVE CHILDREN", "children": [ { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" } ] } ] } ]
-
JavaScriptを使用してJSON配列からデータを読み取る方法は?
以下は、JavaScriptを使用してJSON配列からデータを読み取るためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style
-
配列の最後の要素を出力するJavaScriptコード
以下は、配列の最後の要素を出力するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> bod