JSON.stringfy of large objects with Angular 8

Asked

Viewed 189 times

0

I am starting an application with Angular 8 and have a question that is being complicated to solve.

Is there a practical way to turn a javascript object into a JSON string defining which attributes of it I want to pass? For example: I fear the following Object

{  
   "id":null,
   "nome":"Pedro de Lara",
   "documento":"00000000000",
   "fone1":"1234",
   "municipio":{  
      "id":4861,
      "nome":"Carlos Barbosa",
   }
}

I would like this function to automatically transform the municipality so that it only has the id, for example:

{  
   "id":null,
   "nome":"Pedro de Lara",
   "documento":"00000000000",
   "fone1":"1234",
   "municipio":{  
      "id":4861
   }
}

This example is a small object, but what I need to do is with larger "children" objects.

I’m sorry if the question is too silly, I’m new to the subject and I haven’t found an option that will convince me to be the best.

Thank you.

2 answers

0

In this case, I believe the best way is to work with a model. You create a new file called person.model.ts with the following code:

export class Municipio{
  id: number;
}


export class User {
  id: number;
  nome: string;
documento: number;
fone1: string;
municipio: Municipio = new Municipio();

  constructor(json: any) {
    this.id = json.id;
    this.nome = json.nome;
    this.documento = json.documento;
    this.fone1 = json.fone1;
    this.municipio.id = json.municipio.id;
  }
}

and in its main code, imports the model:

import { User } from "./pessoa.model.ts";

and in the code, when creating a new User using this model, it will only take the county id:

var pessoa = new User({"id":null, "nome":"Pedro de Lara", "documento":"00000000000", "fone1":"1234", "municipio":{"id":4861, "nome":"Carlos Barbosa"}});

In case you want to see it working, can go on this link.

0


I have two tips, you can delete using the javascript delete property:

delete Object.municipio.name;

or using the lib lodash:

$ Yarn add lodash

import _ from lodash;


object.municipio =_.omit(object.municipio, ['nome']);

_.omit-lodash

Regarding the sizes of child objects(nested Objects), there is no limit size for a String in Javascript, the problem is if you are going to send this String in some request, or if the object has a very complex structure; if it is a circular object you will need to convert to JSON before turning into String.

  • Good morning, then, I realized that I would have this circular problem, that’s when I decided to start looking for alternatives. I would need to transform this object to JSON, using JSON.parce?

  • No, manually, it’s like you take from this circular object only what you want. This lib lodash has _.pick, it is unlike _.omit, with this method you take only what you want from an object. Take a look here: https://lodash.com/docs/4.17.15#pick

Browser other questions tagged

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