首页 > 解决方案 > 如何映射json实体?

问题描述

有一种方法可以在 react-native 中映射 json 对象吗?例如,假设我收到以下对象:

{
    "dados": {
        "ultimaAtualizacao": {
            "nome": "Lala"
        }
        "nascimento": "01/01/2001"
    }
}

我想像这样映射它:

{
    "data": {
        "lastUpdate": {
            "name": "Lala"
        }
        "dob": "01/01/2001"
    }
}

考虑到fetch返回第一个对象,可以执行以下代码:

myService.get(url).then(response => this.mapObject(response, []));

//Considering state is initialized and I have the mapedEntity to return correct properties
mapObject(jsonObject, parentProperty) {
    for (let property in jsonObject) {
        if (Array.isArray(jsonObject[property])) {
            this.mapArray(jsonObject[property], [...parentProperty,property]); //Would be something like mapObject function
        } else if (typeof jsonObject[property] === 'object') {
            this.mapObject(jsonObject[property],[...parentProperty,property]);
        } else {
            let prop = this.state;
            for(let k of parentProperty) {
              prop = prop[mapedEntity[k]];
            }
            prop[entidadeMapeada[property]] = jsonObject[property];
        }
    }
}

有某种更简单的方法来实现这一点?

标签: jsonreact-native

解决方案


推荐阅读