-1

I have an object outside of the function that I want to populate with every iteration and call that object after the iteration is done but I am only able to see the last element in my object. How do I add to object instead of replacing?

My code:

let myobj = {};
const func1 = async (arg) => {
  let table_id = result.data.internal_id;
  const response = await axios_Func({ graphQL query });
  console.log(`${response.data.name} - ${table_id}`);
  myobj["name"] = response.data.name;
  myobj["id"] = table_id;
  await func2({ query: graphQL_query, table_id });
}

const func2 = async (result, table_id) => {
  let dev = await getAllTables({ query: tables(123) });
  let prod = await getAllTables({ query: tables(321) });
  let prod_id = new Set();
  result.data.data.table.table_fields.forEach((d) => {
    if (d. connector != null && !(d.name in dev))
      prod_id.add(prod[d.name]["id"]);
  });
  prod_id = [...prod_id];
  prod_id.map((x) => createOne({ query: graphQL_query(x) });
  return Promise.all(prod_id.map((x) => func1({ query: graphQL_query(x) }));
});

const callback = () => console.log(myobj);

const execute = async () => {
  await func1()
  callback()
}

myobj is returning the last element in the object rather than the 5 elements it is supposed to have been populated with.

How do I get my object to have all the elements?

11
  • The object properties should be arrays if you want them to hold multiple values. Or make an array of objects instead of a single object.
    – Barmar
    Commented May 10, 2023 at 16:49
  • Which loop are you talking about? I don't see any loop that updates myobj.
    – Barmar
    Commented May 10, 2023 at 16:50
  • @Barmar func1 and func2 call each other till the function finishes running the forEach in func2
    – nb_nb_nb
    Commented May 10, 2023 at 17:12
  • I see await func2 in func1, but where is func2 calling func1?
    – Barmar
    Commented May 10, 2023 at 17:15
  • @Barmar, once the forEach ends the function stops
    – nb_nb_nb
    Commented May 10, 2023 at 17:16

1 Answer 1

1

You need an array to hold multiple objects.

let myarray = [];
const func1 = async (arg) => {
  let table_id = result.data.internal_id;
  const response = await axios_Func({ graphQL query });
  console.log(`${response.data.name} - ${table_id}`);
  const myobj = {};
  myobj["name"] = response.data.name;
  myobj["id"] = table_id;
  myarray.push(myobj);
  await func2({ query: graphQL_query, table_id });
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.