W
W
WhiteJamer2020-04-23 20:46:48
JavaScript
WhiteJamer, 2020-04-23 20:46:48

Filling an array according to Javascript?

Catalogs.json implements subdirectories by adding a parentId field .
Each product belongs to a specific catalog, respectively, each catalog has a catalogId field categories that have parentID = id of the selected directory: <Keyboards> , <Mice> , etc. and these directories can have their own child directories <Mechanical keyboards> , <Wireless mice>


i.e. nesting can be indefinitely.

I need to somehow have the catalogs array on hand (which contains all the catalogs) and the selectedCatalog constant with the selected catalog id - put all the IDs of the child catalogs into the allIds array and, accordingly, the selectedCatalog value .

Please tell me at least in which direction to dig, because I don’t understand at all how to implement such a nested iteration operation.
I'm developing an app in React, Redux if that matters.

JSON catalogs.json

[
  {
    "id": 1,
    "title": "Девайсы",
    "parentId": null
  },
  {
    "id": 2,
    "title": "Мышки",
    "parentId": 1
  },
  {
    "id": 3,
    "title": "Беспроводные мышки",
    "parentId": 2
  },
  {
    "id": 4,
    "title": "Еще какой то атрибут мышек",
    "parentId": 3
  },
]


const catalogs = ... вытянутый из JSON массив
 const selectedCatalog = ...id выбранного каталога
 const allIds = [] // Пустой массив который нужно наполнить
 
// Какой то процесс перебора который я никак не могу реализовать

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2020-04-23
@Whitejamer

Are you trying to reinvent the faceted filter ? Perhaps it will be easier to take a ready-made implementation.
(the first link that came across for the query "faceted search react" https://react.rocks/tag/Faceted_Search)

D
Dmitry, 2020-04-23
@crystalbit

const allIds = catalogs.filter(it => it.parentId === selectedCatalog).map(it => it.id).concat([ selectedCatalog ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question