如何在JavaScript Node.js中基于单个值dynamic分割数组

我需要基于JavaScript中的单个值dynamic分割数组。

我有一个数组:

var dataStuff = [ { Name: 'Apple', Tag: 'Fruit', Price: '2,5'}, { Name: 'Bike', Tag: 'Sport', Price: '150'}, { Name: 'Kiwi', Tag: 'Fruit', Price: '1,5'}, { Name: 'Knife', Tag: 'Kitchen', Price: '8'}, { Name: 'Fork', Tag: 'Kitchen', Price: '7'} ]; 

我期望数组通过标签拆分,例如。

 var Fruit = [ { Name: 'Apple', Tag: 'Fruit', Price: '2,5'}, { Name: 'Kiwi', Tag: 'Fruit', Price: '1,5'} ]; var Sport = [ { Name: 'Bike', Tag: 'Sport', Price: '150'} ]; var Kitchen = [ { Name: 'Knife', Tag: 'Kitchen', Price: '8'}, { Name: 'Fork', Tag: 'Kitchen', Price: '7'} ]; 

如果在dataStuff数组中会有更多的标签,那么结果会更多的数组。 无论如何,我不知道我该怎么做。 我使用node.js + Jade(查看),我认为最好的想法是在视图中这样做,因为我必须把每个数组放在表中 。 也许这样的事情:

 // Basic table tbody - each item in dataStuff tr td= item.Name td= item.Tag td= item.Price // Other tables - each item in dataStuff item.Tag.push(item); // adding items to array based on Tag // probably it won't work // but still how should i draw table? 

我会很感激任何帮助

你可以使用分组项目的对象。 它适用于任何标签,并允许使用Object.keys(grouped)的所有标签列表,如果需要的话。

 var dataStuff = [{ Name: 'Apple', Tag: 'Fruit', Price: '2,5' }, { Name: 'Bike', Tag: 'Sport', Price: '150' }, { Name: 'Kiwi', Tag: 'Fruit', Price: '1,5' }, { Name: 'Knife', Tag: 'Kitchen', Price: '8' }, { Name: 'Fork', Tag: 'Kitchen', Price: '7' }], grouped = Object.create(null); dataStuff.forEach(function (a) { grouped[a.Tag] = grouped[a.Tag] || []; grouped[a.Tag].push(a); }); document.write(Object.keys(grouped)); document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>'); 

如果您的标签名称是事先知道和有限的

然后干脆

 var Fruit = dataStuff.filter(function(val){ return val.Tag == "Fruit"; }); var Sport = dataStuff.filter(function(val){ return val.Tag == "Sport"; }); var Kitchen = dataStuff.filter(function(val){ return val.Tag == "Kitchen"; }); 

或者你可以创build一个JSON对象来保持标签名称

 var tags = { "Fruit" : [], "Sport" : [], "Kitchen" : [], }; for(var tag in tags) { tags[tag] = dataStuff.filter(function(val){ return val.Tag == tag; }); } 

现在tags.Fruit会给你Fruitarrays。