Рекурсивная функция с Объектом в JS - PullRequest
0 голосов
/ 05 мая 2018

У меня есть массив, содержащий объекты, которые могут иметь n-й уровень глубины.

Примерно так:

const settings = [

    {path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
    {path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
        {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
              {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}  

        ]}  
    ]}

]

Мне нужно добавить в другой массив только свойство 'Url' и свойство children, если оно есть, но с сохранением глубины.

Итак, новый массив должен выглядеть так:

const newArray = [

    {url: '/pictures'},
    {url: '/user/:username', children:[
        {url: '/user/:username/highlights', children:[
                {url: '/user/:username/highlights'} 
        ]}  
    ]}

]

Вы можете мне помочь?

Спасибо

Ответы [ 3 ]

0 голосов
/ 05 мая 2018

Вы можете использовать назначение деструктурирования для требуемых ключей и использовать Array#map для получения нового массива только с одним свойством и использовать Object.assign для дочерних объектов, проверяя дочерние объекты и, если они существуют, извлекайте URL-адреса у детей с помощью рекурсивного вызова функции.

function getUrls(array) {
    return array.map(({ url, children }) =>
        Object.assign({ url }, children && { children: getUrls(children) }));
}

var settings = [{ path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default' }, { path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default' }] }] }],
    urls = getUrls(settings);

console.log(urls);
.as-console-wrapper { max-height: 100% !important; top: 0; }
0 голосов
/ 05 мая 2018

Вот простой и понятный подход наряду с пример скрипки, где вы можете проверить это дальше:

https://jsfiddle.net/eugensunic/pftkosb9/

function findArray(array) {
  var new_array = [];

  for (var i = 0; i < array.length; i++) {
    if (array[i].url) {
      let obj = {};
      obj['url'] = array[i].url;
      obj['children'] = array[i].children;

      new_array.push(obj);

    }
    if (Array.isArray(array[i].children)) {
      new_array = new_array.concat(findArray(array[i].children));
    }
  }
  return new_array;
}

console.log(findArray(settings));
0 голосов
/ 05 мая 2018

const settings = [
    {path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
    {path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
        {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
              {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}  

        ]}  
    ]}
];


function childrenUrls(childrens){
	return childrens.reduce(function(arr, obj){
		var newObj = {url: obj.url};
		if(obj.children) newObj.children = childrenUrls(obj.children);
		return arr.push(newObj), arr;
	}, []);
}


const newArray = childrenUrls(settings);

console.log(newArray);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...