A
A
asus180192021-04-14 19:55:34
React
asus18019, 2021-04-14 19:55:34

How to conditionally pass parameters?

Hello. I make a request to the backend,

const first_name = document.getElementById("input_f_n").value;
        const last_name = document.getElementById("input_l_n").value;
        const email = document.getElementById("input_e").value;
        const houseID = document.getElementById("input_houseID").value;
        const userID = (users.filter(word => word.userID === index))[0].userID;

            const response = await fetch('http://127.0.0.1:8000/api/users/user/update', {
                method: 'PUT',
                headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest',},
                credentials: 'include',
                body: JSON.stringify({
                    userID,
                    first_name,
                    last_name,
                    houseID,
                    email,
                }),
            });


I need to check if the value of first_name, last_name and others is empty, if so, then they do not need to be passed to the body, but I don’t know how to do the check and, depending on the result of the check, pass certain values

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2021-04-19
@asus18019

const first_name = document.getElementById("input_f_n").value;
const last_name = document.getElementById("input_l_n").value;
const email = document.getElementById("input_e").value;
const houseID = document.getElementById("input_houseID").value;
const userID = (users.filter(word => word.userID === index))[0].userID;

const fields = { userID, first_name, last_name, houseID, email };

const body = Object.keys(fields).reduce((acc, key) => {
  if (fields[key] !== '' && fields[key] !== null && fields[key] !== undefined) {
    acc[key] = fields[key];
  }

  return acc;
}, {});

const response = await fetch('http://127.0.0.1:8000/api/users/user/update', {
  method: 'PUT',
  headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest',},
  credentials: 'include',
  body: JSON.stringify(body),
});

Or the check can be organized in another way
//...

const body = { userID, first_name, last_name, houseID, email };

Object.keys(body).forEach(key => {
  if (body[key] === '' || key[key] === null) {
    delete body[key];
  }
});

//...

Well, or completely "on the forehead":
//...

const body = {};

if (first_name !== '') {
  body.first_name = first_name;
}

// Дальше проверки по всем значениям

// ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question