0

I have this code:

<script>
  fbq('track', 'InitiateCheckout', {
    content_ids: {{orderFormProducts}},
    content_type: 'product'
  });
</script>

That gives me the entire array:

content_ids: [
               {
                 "id":"1",
                 "name": "product name",
                 "sku": "10",
                 "skuName": "sku name"
               },
               {
                 "id": "2",
                 "name": "product name",
                 "sku":"20",
                 "skuName": "sku name"
               }
             ]

And what I need is to get only the sku value of all objects inside that array, like so:

content_ids: ["10", "20"]

If I use {{orderFromProducts}}[0].sku I can get the sku value from the 0 indexed object, but I need from all objects inside the array like mentioned before, and {{orderFromProducts}}.sku doesn't work.

Any ideas?

almostamachine
  • 151
  • 1
  • 3
  • 13

3 Answers3

0
content_ids.map(el=>el.sku);

Please http://google.it before you ask, you could have found https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Be warned the .map() function is not available in older browsers.(specifically IE 8 or earlier) – chambo May 31 '17 at 19:01
  • 2
    @chambo even my grandpa isnt using IE8 anymore... – Jonas Wilms May 31 '17 at 19:02
  • @chambo in this case just switch to a loop with `for` :) – GibboK May 31 '17 at 19:07
  • @Jonasw - your grandpa is hip to the game! Despite your hip grandpa, there are still sites that have to maintain compatibility with IE 8 and even older. Figured I'd mention it. Better safe than sorry. YMMV – chambo Jun 01 '17 at 13:37
0

Use array map.

orderFromProducts.map(function(product) {
  return product.sku;
})
Andy_D
  • 4,112
  • 27
  • 19
0

You could use .map() to create a new array populated with sku values.

let content_ids = [{
    "id": "1",
    "name": "product name",
    "sku": "10",
    "skuName": "sku name"
  },
  {
    "id": "2",
    "name": "product name",
    "sku": "20",
    "skuName": "sku name"
  }
];

let skus = content_ids.map(x=>x.sku);

console.log(skus);

For old school browsers like IE 7, use a for instead.

var content_ids = [{
    "id": "1",
    "name": "product name",
    "sku": "10",
    "skuName": "sku name"
  },
  {
    "id": "2",
    "name": "product name",
    "sku": "20",
    "skuName": "sku name"
  }
];

var skus = [];
for (var i = 0, len = content_ids.length; i < len; i++) {
  skus.push(content_ids[i].sku);
}


console.log(skus);
GibboK
  • 71,848
  • 143
  • 435
  • 658