Search code examples
javascriptgoogle-tag-manager

How to get the value of a property of an object in an array in Google Tag Manager


I want to get the value of a property of an object in an array.
I am sending the following items to Google Tag Manager.

items: [{id: 'exampleX', price: '9999'},{id: 'exampleY', price: '9999'},{id: 'exampleZ', price: '9999'}]

Is there any other way to get the price of exampleX but with custom JavaScript?
Or is there a simpler way to get it?

Best Regards,


Solution

  • Check this out:

    const items = [{id: 'exampleX', price: '9999'},{id: 'exampleY', price: '9999'},{id: 'exampleZ', price: '9999'}]
    
    const price = items.filter(e => e.id === "exampleX").pop()?.price;
    console.log(price)

    • items.filter(e => e.id === "exampleX") matches every element where id==="exampleX"
    • .pop() to get the first element from array (might be null if no element is found)
    • ?.price safe unwrap to get property price (undefined if no element was found)

    Update:

    const items = [{id: 'exampleX', price: '9999'},{id: 'exampleY', price: '9999'},{id: 'exampleZ', price: '9999'}]
    
    const price = items[0].price; // first element = index 0
    console.log(price)