我需要在 JavaScript 中根据单个值动态拆分数组。
我有一个数组:
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 数组中会有更多的 Tags 那么在 result 中会有更多的数组。 无论如何,我不知道该怎么做。我正在使用 node.js + Jade(用于查看),我认为最好的想法是在查看时执行此操作,因为我必须将每个数组放在 table 中。也许是这样的:
// 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>');
关于javascript - 如何根据 JavaScript Node.js 中的单个值动态拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36833978/