Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - How does one, within a nested object structure, recursively collect different types of object ids?

I have this data :

{
   "id": 26578,
   "label": "CatA",
   "value": 26578,
   "children": [
     {
        "id": 26579,
        "label": "CatB",
        "value": 26579,
        "children": [
           {
              "id": 26580,
              "label": "CatC",
              "value": 26580,
              "children": null
           },
           {
              "id": 26581,
              "label": "CatD",
              "value": 26581,
              "children": null
           }
        ]
     }
   ]
},

I know the value 26578, I called chosenSubcategoryId

I want to get 2 arrays :

expanded = [26578, 26579]
checked  = [26580, 26581]

I try like this :

const recursion = (item, chosenSubcategoryId) => {
        if (Array.isArray(item)) {
            item.map(item => {
                if (item.id === chosenSubcategoryId) {
                    recursion(item.children, item.id);
                }
            })
        }
}
recursion(this.props.chosenCategory.children, this.props.chosenSubcategory.id);

But not working properly. Please help me ! Thx in advance.

question from:https://stackoverflow.com/questions/65845465/how-does-one-within-a-nested-object-structure-recursively-collect-different-ty

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After you've found the subcategory this condition item.id === chosenSubcategoryId would always be false.

To get the ids of the subcategory items, use an internal recursion. I've used Array.forEach() to iterate the items, add the ids to the respective arrays in the result (res), and iterate the children recursively.

const fn = o => {
  const res = { expanded: [], checked: []};
  
  const recursion = o => {
    if(o.children === null) {
      res.checked.push(o.id);
    } else {
      res.expanded.push(o.id);
      
      o.children.forEach(recursion);
    }
  }
  
  recursion(o);
  
  return res;
};

const obj = {"id":26578,"label":"CatA","value":26578,"children":[{"id":26579,"label":"CatB","value":26579,"children":[{"id":26580,"label":"CatC","value":26580,"children":null},{"id":26581,"label":"CatD","value":26581,"children":null}]}]};

const result = fn(obj);

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...