0

I have a function that returns an array with data. Then I create a variable to hold the object. And I pass a function call to one of the keys. I need to get the length of the array before calling the function and pass it to the key. How can i do this?

const arrFunc = () => {
  let result = [];

  //add value to array

  return result;
};

let result = {
  length: //here I need to display the number (the length of the "result" array)
    array: arrFunc(),
};

console.log(result);
  • Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Ivar Aug 25 '22 at 07:49
  • 2
    Do you really need that though? Can't you call `result.array.length` to get the length instead of `result.length`? – Ivar Aug 25 '22 at 07:50
  • yes i tried but i need to do it before calling the function. In the console I get an error - array is not defined –  Aug 25 '22 at 07:53
  • That doesn't make much sense. The `result` returned from your `arrFunc` doesn't exist before calling the function so it is impossible to get the length of something that doesn't exist yet. – Ivar Aug 25 '22 at 07:54

1 Answers1

-1

I'm sure there are plenty of better ways to achieve your requirement. One of the way should be improve your arrFunc function to directly return your expected result:

const arrFunc = () => {
    let result = [];

    result.push('something');

    return {
        length: result.length,
        array: result,
    };
};

Else I assuming you want to do it with based on the example you provided:

const arrFunc = () => {
  let result = [];

  result.push('something');

  return result;
};

/* return the expected result from an anonymous function */
let result = (() => {
  const array = arrFunc();
  const length = array.length;

  return { length, array }
})();

console.log(result);
Stern Chen
  • 303
  • 1
  • 8