Нахождение позиции супер вложенного массива объектов - PullRequest
0 голосов
/ 23 марта 2019

Я пытаюсь найти точное положение и получить доступ ко всем свойствам супер вложенного массива объектов.

Я изо всех сил пытаюсь создать функцию, в которой, если я задаю индексный номер в качестве входного параметра, он должен дать мне свою позицию в массиве, а также получить доступ ко всем возвращаемым свойствам.

Вот пример массива объекта

Я тоже в порядке с ES6 и выше решением

{
	"name": "branch 1",
	"index": 1,
	"children": [{
			"name": "sub child 1",
			"index": 2,
			"children": [{
				"name": "subx2 child 1",
				"index": 3,
				"children": [{
						"name": "subx3 child 1",
						"index": 4,
						"children": [{
								"name": "subx4 child 1",
								"index": 21
							},
							{
								"name": "subx4 child 2",
								"index": 18
							}
						]
					},
					{
						"name": "subx3 child 2",
						"index": 6,
						"children": [{
								"name": "subx4 child 1",
								"index": 7
							},
							{
								"name": "subx4 child 2",
								"index": 21
							}
						]

					},
					{
						"name": "subx3 child 3",
						"index": 22
					}
				]
			}]
		},
		{
			"name": "sub child 2",
			"index": 28
		}
	]
}

Да, я знаю, что этот объект json достаточно страшен, чтобы тратить время и решать. Любая помощь очень ценится.

например, если мое имя функции findChildIndex (22) , оно должно вернуть мне что-то вроде этого x.children [0] .children [0] .children [2]

Спасибо!

Ответы [ 3 ]

3 голосов
/ 23 марта 2019

Вы можете рекурсивно собрать индексы в массивах children, которые ведут к целевому индексу:

function findIndexNested(data, index) {
    if (data.index === index) return [];
    let result;
    const i = (data.children || []).findIndex(child => {
        return result = findIndexNested(child, index)
    });
    if (result) return [i, ...result];
}
function findByPath(data, path) {
    for (let i of path) data = data.children[i];
    return data
}
// Sample data
const data = {"name": "branch 1","index": 1,"children": [{"name": "sub child 1","index": 2,"children": [{"name": "subx2 child 1","index": 3,"children": [{"name": "subx3 child 1","index": 4,"children": [{"name": "subx4 child 1","index": 21},{"name": "subx4 child 2","index": 18}]},{"name": "subx3 child 2","index": 6,"children": [{"name": "subx4 child 1","index": 7},{"name": "subx4 child 2","index": 21}]},{"name": "subx3 child 3","index": 22}]}]},{"name": "sub child 2","index": 28}]}
const index = 22
const result = findIndexNested(data, index);
console.log("Found index " + index + " via these child indexes: " + result);
console.log("The object is", findByPath(data, result));
2 голосов
/ 23 марта 2019

Вы можете использовать рекурсию и проверить, существует ли children элемента, используйте цикл for, чтобы выполнить итерацию по всем children и рекурсивно применить функцию каждого дочернего элемента

const obj = {
	"name": "branch 1",
	"index": 1,
	"children": [{
			"name": "sub child 1",
			"index": 2,
			"children": [{
				"name": "subx2 child 1",
				"index": 3,
				"children": [{
						"name": "subx3 child 1",
						"index": 4,
						"children": [{
								"name": "subx4 child 1",
								"index": 21
							},
							{
								"name": "subx4 child 2",
								"index": 18
							}
						]
					},
					{
						"name": "subx3 child 2",
						"index": 6,
						"children": [{
								"name": "subx4 child 1",
								"index": 7
							},
							{
								"name": "subx4 child 2",
								"index": 21
							}
						]

					},
					{
						"name": "subx3 child 3",
						"index": 22
					}
				]
			}]
		},
		{
			"name": "sub child 2",
			"index": 28
		}
	]
}

function find(obj,index){
  if(obj.children){
    for(let i = 0;i<obj.children.length;i++){
      let x = find(obj.children[i],index);
      if(x) return {...x,pos:i};
    }

  }
  return obj.index === index ? obj : false;
}

console.log(find(obj,21))
1 голос
/ 23 марта 2019

Если я правильно понял ваш вопрос, вы можете сделать что-то вроде этого:

const func=(obj,index, nested=0)=>{
    return Obj.index===index ? {obj, nested} : func(obj.children,index, nested+1)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...