Search code examples
javascriptjavascript-objects

How-to extract Object out of a Function?


Is it possible to extract an Object out of a Function with JavaScript?

The function I received inside of an Object:

function item(){ let product = { name: name, price: price } }

I want to extract the Object: product out of that function. Caveat: The function may not be changed.

EDIT: Solved. I went on by parsing the function, and creating an array out of the object:

let text ="function item(){ let product = { name: name, price: price }}";

function toArray(x) {
if(x.match('function')) {
    let arr = [];
    let z = x.split(/{/gm)
        for(let i = 0; i< z.length;i++) {
            if(z[i].match(':')) {
            let parsed = z[i].replaceAll('}','').replace(/\s/g,'')
            let finals = parsed.split(',')
            for(let j=0;j<finals.length;j++) {
            arr.push(finals[j].replace(':',','))
        }
            return arr;
        }
    }
}
}
console.log(toArray(text))

Solution

  • I guess the only way is to eval the function's body:

    const name = 'name', price = 3;
    
    function item(){ let product = { name: name, price: price } }
    
    {
      const src = item.toString().match(/(?<=[^{]+\{).+(?=\})/)[0];
      console.log(eval(src + ';product'));
    }