поиск по дереву

149
20 декабря 2019, 14:20

Здравствуйте у меня есть дерево в таком виде

[
    {
        "name": "InvolvementType",
        "children": [
            {
                "name": "FULL_TIME",
                "children": null
            },
            {
                "name": "PARTIAL",
                "children": null
            },
            {
                "name": "EPISODIC",
                "children": null
            }
        ]
    },
    {
        "name": "IncomeStatus",
        "children": [
            {
                "name": "BILLABLE",
                "children": null
            },
            {
                "name": "NOT_BILLABLE",
                "children": null
            }
        ]
    },
    {
        "name": "technology",
        "children": [
            {
                "name": "Android",
                "children": null
            },
            {
                "name": "IOS",
                "children":[
                   {
    name: 'Objective C',
    children: null
    },
    {
    name: 'Swift',
    children: null
    }
                ]
            }
        ]
    }
]

мне нужно выбрав "swift" понимать что этот элимент дерева относится именно к "technology" а не к "InvolvementType". Как сделать поиск по дереву?

Answer 1

Не совсем понятно, что вы имеете ввиду. Я сделал функцию findByName, которая рекурсивно обрабатывает массив, и возвращает массив вида ["technology", "IOS", "Swift"] который хранит путь он родителя до нужного элемента,

const array = [{ 
    "name": "InvolvementType", 
    "children": [{ 
        "name": "FULL_TIME", 
        "children": null 
      }, 
      { 
        "name": "PARTIAL", 
        "children": null 
      }, 
      { 
        "name": "EPISODIC", 
        "children": null 
      } 
    ] 
  }, 
  { 
    "name": "IncomeStatus", 
    "children": [{ 
        "name": "BILLABLE", 
        "children": null 
      }, 
      { 
        "name": "NOT_BILLABLE", 
        "children": null 
      } 
    ] 
  }, 
  { 
    "name": "technology", 
    "children": [{ 
        "name": "Android", 
        "children": null 
      }, 
      { 
        "name": "IOS", 
        "children": [{ 
            name: 'Objective C', 
            children: null 
          }, 
          { 
            name: 'Swift', 
            children: null 
          } 
        ] 
      } 
    ] 
  } 
]; 
 
const findByName = (array, name, tail = []) => { 
  for (const obj of array) { 
    if (obj.name === name) { 
      tail.push(obj.name); 
      return tail; 
    } 
    if (obj.children) { 
      const childrenTail = findByName(obj.children, name, [...tail].concat(obj.name)); 
      if (childrenTail.length) return childrenTail; 
    } 
  } 
  return []; 
} 
 
console.log(findByName(array, 'EPISODIC')); 
console.log(findByName(array, 'Swift')); 
console.log(findByName(array, ''));

READ ALSO
Открыть конкретный блок, react

Открыть конкретный блок, react

Вопрос в следующем, имеется, допустим, 4 кнопки, при клике на кнопку текст в ней должен изменяться на "Открыто", сейчас же проблема в том, что...

142
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'username' in 'where clause'

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'username' in 'where clause'

Не могу понять в чем проблема Есть таблица, В ней есть usergroupid и username

149