首页 > 解决方案 > 如何在谷歌标签管理器中获取数组中对象的属性值

问题描述

我想获取数组中对象的属性值。
我将以下项目发送到 Google 跟踪代码管理器。

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

除了使用自定义 JavaScript,还有其他方法可以获取 exampleX 的价格吗?
或者有没有更简单的获取方式?

此致,

标签: javascriptgoogle-tag-manager

解决方案


看一下这个:

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")匹配每个元素id==="exampleX"
  • .pop()从数组中获取第一个元素(如果没有找到元素,可能为 null)
  • ?.price安全展开以获取房产价格(如果未找到任何元素,则未定义)

更新:

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)


推荐阅读