1

I update an object. This object is an array which can have a length from one to five. This is my object ["max", "dog"].

Now a post method is to be called. It is so if the user has only 2 things filled in, only two things should be sent there. If 5 then 5 (see example for a better explanation.) Does anyone have an idea how best to set this up?

const tag = ["max", "dog"]
const updateInterest = () => {
    axios
      .post("...", {
        first1: max,
        first2: dog,
        // first3: ...,
        // first4: ...,
        // first4: ...,
      })
      .then((res) => {
        if (res.status === 200) {
          // API update interest
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

What I try

const tag = ["max", "dog"]
const updateInterest = () => {
    const object = "";
    tags.map((tag, index) =>{
      console.log(tag + " " + index)
      object = 
        `first${index}`: `${tag}`,
      
  })
    axios
      .post("...", {
        object
      })
      .then((res) => {
        if (res.status === 200) {
          // API update interest
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

My loop doesn't really make much sense. How can I add this to an object so that it can be sent in later in an API?

Kazim
  • 175
  • 9

2 Answers2

1

You can use Object.fromEntries() to map an array of arrays to object, like in the following example:

const arr = ["max", "dog"];

const mapped = arr.map((el, i) => [`first${i+1}`, el]);


console.log(Object.fromEntries(mapped))
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
1

You can also use Array.prototype.reduce() to achieve the same thing:

const arr = ['cat', 'dog'];

const obj = arr.reduce((acc, cur, i) => ((acc[`first${i + 1}`] = cur), acc), {});

console.log(obj);

Reference: Convert Array to Object

brc-dd
  • 10,788
  • 3
  • 47
  • 67