How to map json entities?

Asked

Viewed 661 times

4

I wanted to know if there is any way to map json objects in React-Native. For example, let’s say I get the following json:

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

and I wanted to map to an object:

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

Whereas this comes from a fetch, it would be possible to do so as follows:

meuServico.get(url).then(resposta => this.mapeiaObjeto(resposta, []));

//Considerando que o state já está inicializado
//Considerando que eu já tenha uma entidadeMapeada pra retornar as propriedades corretas
mapeiaObjeto (objetoJson, propriedadePai) {
    for (let propriedade in objetoJson) {
        if (Array.isArray(objetoJson[propriedade ])) {
            mapeiaArray(objetoJson[propriedade], [...propriedadePai,propriedade]); //Seria algo análago a esse método
        } else if (typeof objetoJson[propriedade] === 'object') {
            this.mapeiaObjeto(objetoJson[propriedade],[...propriedadePai,propriedade]);
        } else {
            let prop = this.state;
            for(let chave of propriedadePai) {
              prop = prop[entidadeMapeada[chave]];
            }
            prop[entidadeMapeada[propriedade]] = objetoJson[propriedade];
        }
    }
}

My question is, is there any simpler way, whether with some framework or with own resources of React-Native, to do this?

  • 1

    how will you know which property to map?

  • @Vencovsky in that code of mine, the object entidadeMapeada guard which key is corresponding to which name. For example, { "data": "dados", "dob": "nascimento"} so on. In this case, I wanted to know if there is any way I can create a class and it already generate the object for me natively in React, like Annotations in java

1 answer

5


Using the package deep-map-Keys you can change all keys of an object recursively so:

import deepMapKeys from "deep-map-keys";

let response = {
  data: {
    lastUpdate: {
      name: "Lala"
    },
    dob: "01/01/2001"
  }
};
let dictionary = {
  data: "dados",
  lastUpdate: "ultimaAtualizacao",
  name: "nome",
  dob: "nascimento"
};

let translatedKeys = deepMapKeys(response, key => {
  return dictionary[key];
});

console.log(translatedKeys);

Edit STACKOVERFLOW-PT/368716


"@Marcelorafael the idea would be to create a model and when I received the json object, it already "inject" the values in this object, basically... - Felipe Avelar"

It would be difficult to identify which value goes in which field of this model you spoke of.

Suppose we use the deep-map

import deepMap from "deep-map"

let modelo = {
  usuarios: [
     //Cada objeto teria que ter <%- name1 %>, <%- name2 %>, etc.
     //O mesmo vale com o email e as ruas
    { nome: "<%- name %>", email: "<%- email %>" },
    { nome: "<%- name %>", email: "<%- email %>" },
    { nome: "<%- name %>", email: "<%- email %>" }
  ],
  ruas: [
    { rua: "<%- street %>", bairro: "<%- district %>" },
    { rua: "<%- street %>", bairro: "<%- district %>" }
  ]
}
let response = {
  users: [
     //aqui, cada chave teria que ter um nome de um modelo
     //name1, name2, etc. E o mesmo vale com os outros
    { name: "Marcelo", email: "[email protected]" },
    { name: "Jonas", email: "[email protected]" },
    { name: "Felipe", email: "[email protected]" },
  ],

}

As you can see, there would have to be a predictable response, so you can match the model to the answer.

Now this example shows the simplest model

let modelo = {
  usuarios: '<%- users %>',
  ruas: '<%- streets %>'
}
let response = {
  users: [
    { name: "Marcelo", email: "[email protected]" },
    { name: "Jonas", email: "[email protected]" },
    { name: "Felipe", email: "[email protected]" },
  ],
  streets: [
    { name: "Test1", district: "Hi"},
    { name: "Test2", district: "Hi2"},
  ]
}

This would be feasible. Only now you would have to translate the keys that were passed in full, the ones that were inside the Arrays.

If you google and search: javascript value annotation I don’t think you’ll find anything, but if you research: java value annotation, the @value from Springboot, which is what I think you’re wanting.

  • This library works on React Native?

  • I only use React, test there, see if it works.

  • 1

    Works! Testing

  • deep-map is the same idea, but just do with the values, if you find interesting, is there.

  • In that case, I could create a class that had those keys?

  • Another doubt, he is able to "translate" arrays?

  • Never tested with class, what would be your idea ? Because the normal would be with a same JSON

  • "... is able to translate arrays, "yes, the deep-map loops into arrays as well.

  • @Marcelorafael the idea would be to create a model and when I received the json object, it already "inject" the values in this object, basically...

  • @Felipeavelar I changed the answer, see if that’s what it was

  • 1

    If not, try changing your question, because there you have created two objects, one in Portuguese and one in English, and the object has not changed, so you think you want to translate the keys. Put a better example if possible, vlw.

  • 1

    @Marcelorafael, I think I expressed myself badly in my last comment, your first example is almost complete. My question is whether I would create a model that, when I passed Answer to the class, it would already "build" my object, but I believe that the first example already suits me. (:

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.