lukebm
lukebm

Reputation: 161

How to pass data from one function to another function that is an argument of the first function

In the below example, when using getData();, is it possible to access the data contained in its object map within a new function – ie. useData(); – that is an argument of getData();?

const getData = (useData) => {

  const myData = {
    0: { title: 'Hello' },
    1: { title: 'World!' }
  };

  Object.keys(myData).map((item) => {
    useData();
  });
}

getData(console.log(
  /**
   * Somehow access data represented by `myData` and `item`
   * in above object map along the lines of `myData[item].title` 
  */
));

Upvotes: 1

Views: 55

Answers (2)

Arkadiusz Wieczorek
Arkadiusz Wieczorek

Reputation: 451

Do you want to achieve something like that?

You can call useData with some arguments inside map function. You can't call some function like console.log as argument to getData function in this case.

const getData = useData => {
    const myData = {
        0: { title: "Hello" },
        1: { title: "World!" },
    };

    Object.keys(myData).map(item => {
        useData(myData[item]);
    });
};
getData(console.log);

Upvotes: 1

sabithpocker
sabithpocker

Reputation: 15566

Yes, that is the default behaviour. But you need to pass a function(console.log) instead of a function invocation(console.log()) and invoke it only later.

const getData = (useData) => {

  const myData = {
    0: { title: 'Hello' },
    1: { title: 'World!' }
  };

  Object.keys(myData).map((item) => {
    useData.apply(console, [item]);
    useData.apply(console, [ myData[item].title ]);
    //or useData(myData[item].title)
  });
}

getData(console.log);

getData(console.log('something'));

is same as:

let x = console.log('something');
getData(x);

Upvotes: 0

Related Questions