Created
May 9, 2016 18:12
-
-
Save winkerVSbecks/f7941dc5a738cbc25ec37f7aaefbb890 to your computer and use it in GitHub Desktop.
findNode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var componentData = [{ | |
| "id": "0", | |
| "name": "TodoList", | |
| "children": [{ | |
| "id": "0.0", | |
| "name": "INPUT" | |
| }, { | |
| "id": "0.1", | |
| "name": "NgIf" | |
| }, { | |
| "id": "0.2", | |
| "name": "NgFor" | |
| }, { | |
| "id": "0.3", | |
| "name": "LI", | |
| "children": [{ | |
| "id": "0.3.0", | |
| "name": "TodoItem", | |
| "children": [{ | |
| "id": "0.3.0.0", | |
| "name": "INPUT" | |
| }, { | |
| "id": "0.3.0.1", | |
| "name": "LABEL" | |
| }, { | |
| "id": "0.3.0.2", | |
| "name": "BUTTON" | |
| }, { | |
| "id": "0.3.0.3", | |
| "name": "NgIf" | |
| }] | |
| }] | |
| }, { | |
| "id": "0.4", | |
| "name": "LI", | |
| "children": [{ | |
| "id": "0.4.0", | |
| "name": "TodoItem", | |
| "children": [{ | |
| "id": "0.4.0.0", | |
| "name": "INPUT" | |
| }, { | |
| "id": "0.4.0.1", | |
| "name": "LABEL" | |
| }, { | |
| "id": "0.4.0.2", | |
| "name": "BUTTON" | |
| }, { | |
| "id": "0.4.0.3", | |
| "name": "NgIf" | |
| }] | |
| }] | |
| }] | |
| }]; | |
| var component = [ | |
| {id: 1}, | |
| {id: 6, children: [{ id: 2}, { id:3 },{ id: 5}]}, | |
| {id: 7, children: [ | |
| { id:1}, | |
| { id:3}, | |
| { id: 8, children: [{ id:8}, { id: 9}, { id: 34, children: [{ id:8}, { id: 9}, { id: 35}] }]} | |
| ]}, | |
| { id: 5}, | |
| { id: 6} | |
| ]; | |
| const query = 'LI'; | |
| const findNode = node => node.name && node.name === query; | |
| // const flatten = list => list.reduce( | |
| // (a, b) => a.concat(Array.isArray(b.children) ? flatten(b.children) : b), [] | |
| // ); | |
| const copyParent = parent => { | |
| const parentOnly = Object.assign({}, parent, { children: undefined }); | |
| return [parentOnly, ...flatten(parent.children)]; | |
| }; | |
| const flatten = list => list.reduce((a, b) => { | |
| return a.concat(Array.isArray(b.children) ? copyParent(b) : b); | |
| }, []); | |
| const flattenedData = flatten(componentData); | |
| console.log('#', flattenedData.find(findNode)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment