@newaitix

Как правильно сложить все в массив?

var asd=[
	{
		parentCategoryId: 0,
		name: "Test category",
		categoryLevel: 0,
		itemId: 1874249,
		categoryId: 20
	},
	{
		parentCategoryId: 0,
		name: "Competitors",
		categoryLevel: 0,
		itemId: 1874249,
		categoryId: 52
	},
	{
		parentCategoryId: 0,
		name: "Market Regions",
		categoryLevel: 0,
		itemId: 1874249,
		categoryId: 8
	},
	{
		parentCategoryId: 0,
		name: "Strategic themes",
		categoryLevel: 0,
		itemId: 1874249,
		categoryId: 9
	},
	{
		parentCategoryId: 8,
		name: "Europe",
		categoryLevel: 1,
		itemId: 1874249,
		categoryId: 13
	},
	{
		parentCategoryId: 9,
		name: "M,A",
		categoryLevel: 1,
		itemId: 1874249,
		categoryId: 18
	},
	{
		parentCategoryId: 13,
		name: "Finland",
		categoryLevel: 2,
		itemId: 1874249,
		categoryId: 15
	}
];


i=0;
result=[];
temp={};
temp2={};

function step(){
	if(i<asd.length){
		if(asd[i].parentCategoryId==0){
			result[asd[i].categoryId]=asd[i].name;
			i++;
			step();
		}else{
			if(temp[asd[i].parentCategoryId]==undefined)
				temp[asd[i].parentCategoryId]=asd[i].name;
			else
				temp[asd[i].parentCategoryId]='-'+asd[i].name;
			i++;
			step();
		}
	}else{
		for(var j in temp){
			if(result[j]!=undefined){
				result[j]=result[j]+' - '+temp[j];
			}else{
				temp2[j]=temp[j];
			}
		}
		//result=result.filter(element=>element!==null);
		console.log(result);
		console.log(temp2);
	}
}
step();

если parentCategoryId == 0 то кладем в result.
Иначе нужно собрать все в кучу
Finland - parentCategoryId: 13 поэтому добавляем к categoryId 13, Europe - parentCategoryId: 8 поэтому добавляем к categoryId 8, Market Regions - parentCategoryId: 0 поэтому кладем в массив.
По результату должно получиться
[
"Market Regions - Europe - Finland"
"Strategic themes - M,A"
"Test category"
"Competitors"
]

Не понимаю как все рекурсивно добавить.
  • Вопрос задан
  • 209 просмотров
Решения вопроса 2
@StockholmSyndrome
если массив всегда отсортирован по categoryLevel, то строчку
.sort((a, b) => a.categoryLevel - b.categoryLevel)
можно убрать
const groupData = (arr) => {
	return arr
		.sort((a, b) => a.categoryLevel - b.categoryLevel)
		.reduce((acc, curr) => {
			const {categoryLevel, parentCategoryId} = curr;
			const index = acc.findIndex((a) => 
				(a[categoryLevel - 1] || {}).categoryId === parentCategoryId);
			if (index !== -1) {
				acc[index][categoryLevel] = curr;
			} else {
				acc.push([curr]);
			}
			return acc;
		}, [])
		.map((a) => a.map((o) => o.name).join(' - '));
};
Ответ написан
0xD34F
@0xD34F Куратор тега JavaScript
function groupNames(arr) {
  const obj = Object.fromEntries(arr.map(n => [ n.categoryId, { ...n } ]));
  const values = Object.values(obj);
  const getNames = n => n ? [ n.name, ...getNames(n.next) ] : [];

  values.forEach(n => n.parentCategoryId && (obj[n.parentCategoryId].next = n));

  return values.filter(n => !n.parentCategoryId).map(n => getNames(n).join(' - '));
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы