Answer the question
In order to leave comments, you need to log in
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
}
api_data = {
id: 25,
head: 'Заголовок',
text: 'Текст статьи',
is_open: true,
text_length: 12
}
apiData = new FormData();
for (const key in article) {
if (key === 'id' || key === 'head' || key === 'text' && article[key] ) {
apiData.append(option, article[key]);
}
}
Answer the question
In order to leave comments, you need to log in
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]);
}
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 questionAsk a Question
731 491 924 answers to any question