简体   繁体   English

从多维数组中提取所有名为x的变量-Javascript

[英]Extract all variables named x from multi dimensional array - Javascript

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. 我已经搜索了在SO和其他地方可以使用的所有内容,但找不到答案,这主要是由于我对JS的了解有限。

Could anyone tell me how to extract values from an array that is similar to the following (enhanced ecommerce array in dataLayer); 谁能告诉我如何从类似于以下内容的数组中提取值(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, eg [name123,name345]. 在这种情况下,我只想提取名称,最后得到另一个仅包含[name123,name345]中值的数组。 I'd like to push this into the dataLayer again, but I think I can do that part myself. 我想再次将其推送到dataLayer中,但是我想自己可以做到这一点。

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 马特

.map为此!

var names = products.map(function(product) { return product.name });

Assuming your name property is always there, it's as simple as that: 假设您的name属性始终存在,就这么简单:

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 :) 如果不关心版本9以下的IE,您也可以使用地图,如@tymeJV指出的那样:)

This was already answered here. 这里已经回答了。

You could use .map or a for loop: 您可以使用.map或for循环:

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

Here is more information on for in loops from MDN 这是有关MDN中for循环的更多信息

here's an example using forEach : 这是使用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) 

What you want to do is pass your array into a map function. 您要做的是将数组传递给map函数。 Example using underscore.js 使用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. 映射函数获取一个数组(或对象),通过迭代器运行每个值,然后返回一个新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM