How to check if nested objects have children or not?

巧了我就是萌 提交于 2019-12-02 13:38:06

问题


I'm new to Javascript/React so I'm not sure how to implement this into my recursive function. I have a nested menu of json objects set up, and want to add little arrows indicating if there is another level to click to or not. Since my menu is made up of heavily nested json objects, I used recursion to go through all the objects and render them as a menu. I will include screenshots to visually explain what I'm trying to do as well.

Does anyone have any ideas on how to check if that layer of objects has children, and if so add an arrow (or anything) to indicate this?

Here is my code:

class Menu extends React.Component {
  state = {
    categories: [],
    objectKeys: null,
    tempKeys: []
  };

  makeMenuLayer = layer => {
    const { objectKeys } = this.state;
    const layerKeys = Object.entries(layer).map(([key, value], index) => {
      return (
        <ul key={key}>
          <div onClick={() => this.handleShowMore(key)}>{key}</div>
          {objectKeys[key] && this.makeMenuLayer(value)}
        </ul>
      );
    });
    return <div>{layerKeys}</div>;
  };

  handleShowMore = key => {
    this.setState(prevState => ({
      objectKeys: {
        ...prevState.objectKeys,
        [key]: !this.state.objectKeys[key]
      }
    }));
  };

  initializeTempKeys = layer => {
    Object.entries(layer).map(([key, value]) => {
      const newTempKeys = this.state.tempKeys;
      newTempKeys.push(key);
      this.setState({ tempKeys: newTempKeys });
      this.initializeTempKeys(value);
    });
  };

  initializeObjectKeys = () => {
    const { tempKeys } = this.state;
    let tempObject = {};
    tempKeys.forEach(tempKey => {
      tempObject[tempKey] = true;
    });

    this.setState({ objectKeys: tempObject });
  };

  componentDidMount() {
    axios.get("https://www.ifixit.com/api/2.0/categories").then(response => {
      this.setState({ categories: response.data });
    });
    const { categories } = this.state;
    this.initializeTempKeys(categories);
    this.initializeObjectKeys();
    this.setState({ categories });
  }

  render() {
    const { categories } = this.state;
    return <div>{this.makeMenuLayer(categories)}</div>;
  }
}

Here is how it currently looks, and I'd like it so any element that has more elements within it have an arrow or something to show there is more data nested (so for this, Apparel, Accessory, Clothing, etc would have arrows):

Here's an example of the type of thing I'm going for:

来源:https://stackoverflow.com/questions/56086870/how-to-check-if-nested-objects-have-children-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!