簡體   English   中英

你如何在 React 中映射 json?

[英]How do you map json in React?

我正在嘗試使用 react 在表中顯示以下 Json,但我不確定如何訪問empresasBodega_Origen y Bodega_Destino 的 JsonArray 中的元素

  {
        "Estado": 1,
        "_id": "5e31ecf510ec6117387548a1",
        "usuarios": "5e262750803c451ca4a27c36",
        "empresas": {
            "_id": "5e2f4c3ef80d8246f0e545d8",
            "Nombre_Empresa": "ING. Y HER. S.A."
        },
        "Tipo_Documento": "AF",
        "Numero_Documento": "1",
        "Bodega_Origen": {
            "_id": "5e2619ccbb29d71aa8455cad",
            "Descripcion": "BODEGA PRINCIPAL"
        },
        "Bodega_Destino": {
            "_id": "5e2629f110b9f32d10524ca5",
            "Descripcion": "BODEGA Obra parma"
        },
        "Responsable": "Mauricio",
        "Estado_Documento": "PR",
        "Observaciones": "",
        "Detalles": [],
        "Fecha_Creacion": "2020-01-29T20:37:09.919Z"
    }

以下是我用來獲取數據並解析它的方法。 您當前正在正確瀏覽數據,但它沒有顯示 Bodega_Origen y la Bodega_Destino 中的數據。

  loadData(){
        var cont = 0;
        console.log('Getting list');
        const activeTab = this.state.activeTab;
        const ids = this.ids;
        const path = activeTab===0?'/empresa/list':'/articulo/list';
        console.log(this.state.listQuery);
        cont++;
        console.log(cont)
        return this.Requests.list(path, this.state.listQuery).then(response=>{
            if(response && response.length !== 0){// El request no ha devuelto un arreglo vacio
                let dt = response;
                dt.map((el,i)=>{
                    let filterProperties = [];//Propiedades de interes
                    filterProperties[i] = {};//Inicializar el objeto para cada elemento del arreglo
                    ids[activeTab].forEach(key=>{
                        if(el[key]._id){
                            el[key] = el[key].nombre;
                        }
                        filterProperties[i][key] = el[key];
                    })
                    return filterProperties;
                });
                console.log(dt);
                let stateData = this.state.data.slice();
                stateData[activeTab] = dt.slice();
                this.setState({data:stateData});
            }else{
                let stateData = this.state.data.slice();
                stateData[activeTab] = [];
                this.setState({data:stateData})
            }
        });
    }

對象本身是不可迭代的。 你不能像 React 中的數組那樣映射對象。 您可以嘗試使用Object.entries(obj) ,然后遍歷這些鍵、值對並獲得您想要的。

要訪問該 json 數據,您需要指定它:

 data.empresas data.Bodega_Origen data.Bodega_Destino
通過這種方式,您可以訪問嵌套的 json 對象。 JSON 是一種對象類型,而不是數組。 希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM