S
S
sdgroup142019-05-22 19:41:48
Angular
sdgroup14, 2019-05-22 19:41:48

How to remove unnecessary data from an object?

Hello everyone ... I wrote the admin panel, somewhere around 15 pages. All right, I'm trying to refactor. Essence of the question:
For example, there is an interface

interface Article {
      id: number,
      head: string,
      text: string
  }

In the course of development... I am writing code without an interface (the above is to make it clear to you which object is at the input and output). So. For example, I received "article" from the api, but by clicking on the head I make an article google and, for example, I count the characters when adding a textarea, and as a result, before saving, this object came out
api_data = {
      id: 25,
      head: 'Заголовок',
      text: 'Текст статьи',
      is_open: true,
      text_length: 12
  }

But when sending, I have to filter out is_open text_length each time, since these properties are not available for writing to the api.
apiData = new FormData();
    for (const key in article) {
      if (key === 'id' ||  key === 'head'  ||  key  === 'text'  && article[key] ) {
         apiData.append(option, article[key]);
      }
    }

Is there any beautiful solution for such manipulations, so that through some function or native method of angular weed out such as is_open, etc.?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zakharov Alexander, 2019-05-22
@sdgroup14

Yes, everything seems to be normal. It is possible not to write key several times:

if (['id', 'head', 'text'].indexOf(key)>=0  && article[key] ) {
         apiData.append(option, article[key]);
}

If important, sometimes it makes sense to add hasOwnProperty()

D
Dmitry Luzanov, 2019-05-22
@dmitry_luzanov

Such is_open and text_length should not be in the article object if they are not directly related to the entity. I would store the state in the component field of the article itself.
But since you have it, there is such an option.

public postArticle({ id, head, text }: Article) {
    const apiFields = { id, head, text };
    const apiData = new FormData();

    for (const key in apiFields) {
      apiData.append(key, apiData[key]);
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question