1

I've searched through everything I can on SO and elsewhere but can't find an answer, this is mostly due to my limited JS knowledge.

Could anyone tell me how to extract values from an array that is similar to the following (enhanced ecommerce array in dataLayer);

var products = [
{ brand: "brandx", category: "categorya", name: "name123" },
{ brand: "brandy", category: "categoryb", name: "name345" }
];

I would just like to extract the name in this case and end up with another array with just the values in, e.g. [name123,name345]. I'd like to push this into the dataLayer again, but I think I can do that part myself.

I did have some success but that was only in selecting the first name value.

Thank you in advance for any help anyone can offer

Matt

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Matt
  • 105
  • 1
  • 2
  • 5
  • 1
    You could use a `for` to go through all elements inside products and select a name ? Something like `for (items in products)` and store each name into another list `names.append(item.name)`. I can't provide an example right now but I guess that's what you need. – Onilol Sep 02 '15 at 15:16

5 Answers5

7

.map is for this!

var names = products.map(function(product) { return product.name });
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Thank you very much, in the end I used @mamoo's reply below thanks to people who still use IE 8 :s, but your answer worked well for me in Chrome. – Matt Sep 03 '15 at 12:19
1

Assuming your name property is always there, it's as simple as that:

var products = [
{ brand: "brandx", category: "categorya", name: "name123" },
{ brand: "brandy", category: "categoryb", name: "name345" }
];

var result = [];
for (var i = 0; i < products.length; i++){
    result.push(products[i].name);
}

If IE below version 9 is not a concern, you can use map as well, as pointed out by @tymeJV :)

mamoo
  • 8,156
  • 2
  • 28
  • 38
  • 1
    Thank you @mamoo, still plenty of IE8 users unfortunately so I used your version. – Matt Sep 03 '15 at 12:20
1

This was already answered here.

You could use .map or a for loop:

var namesArray = [];
for(index in products) {
  namesArray.push(products[index].name);
}
namesArray;
=> [ 'name123', 'name345' ]

Here is more information on for in loops from MDN

Community
  • 1
  • 1
Teresa
  • 75
  • 7
0

here's an example using forEach:

var products = [
{ brand: "brandx", category: "categorya", name: "name123" },
{ brand: "brandy", category: "categoryb", name: "name345" }
];

 var names  = [];
products.forEach(function(x){
names.push(x.name)
})

console.log(names)
maioman
  • 18,154
  • 4
  • 36
  • 42
-1

What you want to do is pass your array into a map function. Example using underscore.js

var newArray=_.map(products, function(value){return value.name})

A map function takes an array (or object), runs each value through an iteree, and returns a new array.

superclone
  • 29
  • 4