Как извлечь из вложенной структуры элементы удовлетворяющие условию?

Пример рабочий:



Есть массив:
const myarr = {
    "id": 1,
    "title": "Профильная часть",
    "placeholder": "Профильная часть",
    "type": "part",
    "typeName": "profile",
    "lectures": 0,
    "practice": 6,
    "homework": 0,
    "content": [
      {
        "id": 2,
        "title": "intermediate current",
        "placeholder": "dadada",
        "type": "module",
        "lectures": 0,
        "practice": 6,
        "homework": 0,
        "content": [
          {
            "id": 3,
            "title": "intermediate current",
            "placeholder": "ccccc",
            "type": "theme",
            "lectures": 0,
            "practice": 6,
            "homework": 0,
            "content": [
              {
                "id": 4,
                "title": "intermediate current",
                "description": "ccccc",
                "placeholder": "zxczcx",
                "period": [
                  {
                    "id": 6,
                    "value": 6,
                    "title": "6 недели"
                  },
                  {
                    "id": 4,
                    "value": 4,
                    "title": "4 недели"
                  }
                ],
                "workControl": [
                  "intermediate",
                  "current"
                ],
                "lectures": 0,
                "practice": 6,
                "homework": 0,
                "type": "practice",
                "content": []
              }
            ]
          }
        ]
      },
      {
        "id": 52,
        "title": "intermediate current",
        "placeholder": "dadada",
        "type": "module",
        "lectures": 0,
        "practice": 6,
        "homework": 0,
        "content": [
          {
            "id": 53,
            "title": "intermediate",
            "placeholder": "ccccc",
            "type": "theme",
            "lectures": 0,
            "practice": 6,
            "homework": 0,
            "content": [
              {
                "id": 54,
                "title": "intermediate",
                "description": "ccccc",
                "placeholder": "zxczcx",
                "period": [
                  {
                    "id": 56,
                    "value": 6,
                    "title": "6 недели"
                  },
                  {
                    "id": 54,
                    "value": 4,
                    "title": "4 недели"
                  }
                ],
                "workControl": [
                  "intermediate"
                ],
                "lectures": 0,
                "practice": 6,
                "homework": 0,
                "type": "practice",
                "content": []
              }
            ]
          }
        ]
      },
]

Что из него нужно достать:

Объекты, у которых в свойстве workControl присутствует значение 'intermediate':

[
   {
      "id":2,
      "title":"intermediate current",
      "placeholder":"dadada",
      "type":"module",
      "lectures":0,
      "practice":6,
      "homework":0,
      "content":[
         {
            "id":3,
            "title":"intermediate current",
            "placeholder":"ccccc",
            "type":"theme",
            "lectures":0,
            "practice":6,
            "homework":0,
            "content":[
               {
                  "id":4,
                  "title":"intermediate current",
                  "description":"ccccc",
                  "placeholder":"zxczcx",
                  "period":[
                     {
                        "id":6,
                        "value":6,
                        "title":"6 недели"
                     },
                     {
                        "id":4,
                        "value":4,
                        "title":"4 недели"
                     }
                  ],
                  "workControl":[
                     "intermediate",
                     "current"
                  ],
                  "lectures":0,
                  "practice":6,
                  "homework":0,
                  "type":"practice",
                  "content":[
                     
                  ]
               }
            ]
         }
      ]
   },
   {
      "id":52,
      "title":"intermediate current",
      "placeholder":"dadada",
      "type":"module",
      "lectures":0,
      "practice":6,
      "homework":0,
      "content":[
         {
            "id":53,
            "title":"intermediate",
            "placeholder":"ccccc",
            "type":"theme",
            "lectures":0,
            "practice":6,
            "homework":0,
            "content":[
               {
                  "id":54,
                  "title":"intermediate",
                  "description":"ccccc",
                  "placeholder":"zxczcx",
                  "period":[
                     {
                        "id":56,
                        "value":6,
                        "title":"6 недели"
                     },
                     {
                        "id":54,
                        "value":4,
                        "title":"4 недели"
                     }
                  ],
                  "workControl":[
                     "intermediate"
                  ],
                  "lectures":0,
                  "practice":6,
                  "homework":0,
                  "type":"practice",
                  "content":[
                     
                  ]
               }
            ]
         }
      ]
   }
]

Рабочий, но громоздкий код и не универсальный:

let arr = [];
let currentControl = myarr.map(part => {
					part.content.filter(elem => {
						if(elem.content.length){
							console.log('elee', elem.title)
							elem.content.filter(elem2 => {
								if(elem2.content.length){
									console.log('el2', elem2)
									elem2.content.filter(elem3 => {
										console.log('el3', elem3)
										if(elem3.workControl.filter(control => {
											console.log('control', control)
											if(control == 'intermediate'){
												arr.push(elem)
											}
										}))
										return []
									})
									return  []
								}
							})
							return []
						}
					})
				});
document.getElementById("dd").prepend(JSON.stringify(arr))

Подскажите как зациклить его через map или reduce без использования функций.
  • Вопрос задан
  • 244 просмотра
Пригласить эксперта
Ответы на вопрос 2
0xD34F
@0xD34F Куратор тега JavaScript
Рекурсия есть:

const getNestedData = (data, test) => Object
  .values(data instanceof Object ? data : {})
  .reduce((acc, n) => (
    acc.push(...getNestedData(n, test)),
    acc
  ), test(data) ? [ data ] : []);


const result = getNestedData(arr, n => n?.workControl?.includes?.('intermediate'));

Рекурсии нет:

function getNestedData(data, test) {
  const result = [];

  for (const stack = [ data ]; stack.length;) {
    const n = stack.pop();

    if (n instanceof Object) {
      stack.push(...Object.values(n).reverse());
    }

    if (test(n)) {
      result.push(n);
    }
  }

  return result;
}

// или

function getNestedData(data, test) {
  const result = [];
  const stack = [];

  for (let i = 0, arr = [ data ]; i < arr.length || stack.length; i++) {
    if (i === arr.length) {
      [ i, arr ] = stack.pop();
    } else {
      if (test(arr[i])) {
        result.push(arr[i]);
      }

      if (arr[i] instanceof Object) {
        stack.push([ i, arr ]);
        [ i, arr ] = [ -1, Object.values(arr[i]) ];
      }
    }
  }

  return result;
}
Ответ написан
Alexandroppolus
@Alexandroppolus
кодир
function getIntermediateItems(tree, result = []) {
  tree?.forEach((item) => {
    if (item.workControl?.includes('intermediate')) {
      result.push(item);
    }
    getIntermediateItems(item.content, result);
  });
  return result;
}

const arr = getIntermediateItems(myarr);
document.getElementById("dd").prepend(JSON.stringify(arr, '', 4))
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
06 нояб. 2024, в 03:35
5000 руб./за проект
06 нояб. 2024, в 00:20
1000 руб./за проект
06 нояб. 2024, в 00:03
40000 руб./за проект