Задать вопрос

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

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



Есть массив:
const myarr = [
  {
    "id": 0,
    "title": "Базовая часть",
    "placeholder": "Базовая часть",
    "type": "part",
    "typeName": "base",
    "lectures": 0,
    "practice": 0,
    "homework": 0,
    "content": []
  },
  {
    "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": []
              }
            ]
          }
        ]
      },
      {
        "id": 22,
        "title": "нету",
        "placeholder": "dadada",
        "type": "module",
        "lectures": 0,
        "practice": 6,
        "homework": 0,
        "content": [
          {
            "id": 23,
            "title": "нету",
            "placeholder": "ccccc",
            "type": "theme",
            "lectures": 0,
            "practice": 6,
            "homework": 0,
            "content": [
              {
                "id": 24,
                "title": "нету",
                "description": "ccccc",
                "placeholder": "zxczcx",
                "period": [
                  {
                    "id": 26,
                    "value": 6,
                    "title": "6 недели"
                  },
                  {
                    "id": 24,
                    "value": 4,
                    "title": "4 недели"
                  }
                ],
                "workControl": [],
                "lectures": 0,
                "practice": 6,
                "homework": 0,
                "type": "practice",
                "content": []
              }
            ]
          }
        ]
      }
    ]
  }
]

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

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

[
  {
    "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": 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(elem3)
											}
										}))
										return []
									})
									return  []
								}
							})
							return []
						}
					})
				});
document.getElementById("dd").prepend(JSON.stringify(arr))

Подскажите как зациклить его через map или reduce без использования функций.
  • Вопрос задан
  • 305 просмотров
Подписаться 3 Средний 1 комментарий
Решения вопроса 2
0xD34F
@0xD34F Куратор тега JavaScript
Как будем проверять, что значение нам подходит:

const isValid = n => n.workControl?.includes('intermediate');

Рекурсия есть:

const getFromTree = (tree, childrenKey, test) =>
  Array.isArray(tree)
    ? tree.reduce((acc, n) => (
        test(n) && acc.push(n),
        acc.push(...getFromTree(n[childrenKey], childrenKey, test)),
        acc
      ), [])
    : [];

const result = getFromTree(tree, 'content', isValid);

или

function* getNestedData(data, test) {
  if (test(data)) {
    yield data;
  }

  if (data instanceof Object) {
    for (const k in data) if (Object.hasOwn(data, k)) {
      yield* getNestedData(data[k], test);
    }
  }
}

const result = [...getNestedData(tree, isValid)];

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

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

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

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

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

  return result;
}

или

const getFromTree = function*(tree, childrenKey, test) {
  const stack = [];

  for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
    if (i === arr.length) {
      [ i, arr ] = stack.pop();
    } else {
      if (test(arr[i])) {
        yield arr[i];
      }

      stack.push([ i, arr ]);
      [ i, arr ] = this(arr[i][childrenKey]);
    }
  }
}.bind(x => [ -1, x instanceof Array ? x : [] ]);
Ответ написан
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))
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Похожие вопросы