从React中的父JSON数据获取所有子级

时间:2019-05-06 11:04:05

标签: javascript json reactjs

这是我的json数据的示例

[
   {
      "Id":"114",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
   {
      "Id":"115",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
      "Id":"44",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"45",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"50",
      "Padre":"Telefonia",
      "Hijo":"Audio"
   },
   {
      "Id":"52",
      "Padre":"Telefonia",
      "Hijo":"Configuracion"
   },
   {
      "Id":"70",
      "Padre":"Telefonia",
      "Hijo":"Rutas"
   }
]

到目前为止,我已经在console.log中获得了以下数据:

(3) [{…}, {…}, {…}]
0: {Padre: "CRM", Hijo: "Argumentarios", Description: "SALUD NORMAL", Id: "114"}
1: {Padre: "Permisos", Hijo: "root", Description: "Usuarios", Id: "44"}
2: {Padre: "Telefonia", Hijo: "Audio", Description: "Locuciones", Id: "50"}

我需要显示每个父元素的所有子元素。 我正在创建一个菜单,并且希望与每个父级关联的子菜单出现。我希望孩子们不要再出现了。在我的json父级中,它是Padre,而孩子是Hijo(西班牙语)。 这是我的原始代码:

    componentWillMount(){
        fetch('fake-son.php')
        .then(response => response.json())
        .then(menuSubmenu =>{

            const result = [];
            const map = new Map();
            for (const item of menuSubmenu) {
                if(!map.has(item.Padre)){
                    map.set(item.Padre, true);    // set any value to Map

                    result.push({
                        Padre: item.Padre,
                        Hijo: item.Hijo,
                        Description: item.Description,
                        Id:item.Id
                    });
                }
            }
                this.setState({ 
                    menuSubmenu:this.state.menuSubmenu.concat(result)
                })

            console.log(result);         

        })
    }

您能帮我向所有孩子们介绍他们父亲的情况吗?非常感谢

4 个答案:

答案 0 :(得分:1)

您可以使用array.reduce创建类似的关系,

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      parentList: []
    };
  }

  componentDidMount() {
    //call your rest api here...
    const list = [{
        "Id": "114",
        "Padre": "CRM",
        "Hijo": "Argumentarios"
      },
      {
        "Id": "115",
        "Padre": "CRM",
        "Hijo": "Argumentarios"
      },
      {
        "Id": "44",
        "Padre": "Permisos",
        "Hijo": "root"
      },
      {
        "Id": "45",
        "Padre": "Permisos",
        "Hijo": "root"
      },
      {
        "Id": "50",
        "Padre": "Telefonia",
        "Hijo": "Audio"
      },
      {
        "Id": "52",
        "Padre": "Telefonia",
        "Hijo": "Configuracion"
      },
      {
        "Id": "70",
        "Padre": "Telefonia",
        "Hijo": "Rutas"
      }
    ];
    
    const PadreMap = list.reduce((acc, obj) => {
      if (!acc[obj.Padre]) {
        acc[obj.Padre] = {
          ...obj,
          Hijo: [obj.Hijo]
        };
      } else {
        !acc[obj.Padre].Hijo.includes(obj.Hijo) && acc[obj.Padre].Hijo.push(obj.Hijo)
      }
      return acc;
    }, {});
    
    this.setState({parentList: Object.keys(PadreMap).map((padre) => ({
      name: padre,
      children: PadreMap[padre].Hijo
    }))})
  }

  render() {
    return <div >{
      this.state.parentList.map(parent => <ul>{parent.name}:
      {parent.children.map(hijo => <li>{hijo}</li>)}
      </ul>)
    }< /div>
  }
}

ReactDOM.render( < Demo / > , document.getElementById('app'));
li{
  margin-left: 30px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

答案 1 :(得分:0)

是的,您可以通过命令object.toSource()来显示它,它显示所有对象属性...

答案 2 :(得分:0)

使用以下代码块代替地图代码

menuSubMenu.forEach((item)=>{
  if(item){
   const key = item.Padre;
   if(!map.get(key)){
     map.set(key,[item]);
  }else{
  map.get(key).push(item); // if you need just child name then push item.Hijo
 }

}  });

此代码将为您提供唯一的父地图,如下所示 要将其迭代为数组并合并结果

let results = Array.from(map);// in results [0] index will have name of parent [1] index will have the array of values

enter image description here

答案 3 :(得分:0)

您可以像这样简单地完成操作

let data=[
   {
      "Id":"114",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
   {
      "Id":"115",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
  {
      "Id":"44",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"45",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"50",
      "Padre":"Telefonia",
      "Hijo":"Audio"
   },
   {
      "Id":"52",
      "Padre":"Telefonia",
      "Hijo":"Configuracion"
   },
   {
      "Id":"70",
      "Padre":"Telefonia",
      "Hijo":"Rutas"
   }
]

const mapChildren=()=>{
  const newData=data.reduce(function (r, a) {
        a=Object.assign({},a)
        r[a.Padre] = r[a.Padre] || [];
        r[a.Padre].push(a);
    delete a.Padre;
        return r;
    }, Object.create(null));
  return newData;
}


console.log('#Children:',mapChildren(),typeof(mapChildren()))
console.log('#PArents:',Object.keys(mapChildren()))