问题
I need to split array dynamically based on single value in JavaScript.
I've got an array:
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'}
];
And i expect arrays split by Tag, eg.
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'}
];
If in dataStuff array will be more Tags then in result will be more arrays. Anyway i don't have idea how should I do this. I'm using node.js + Jade (for view), and i think the best idea will be do this at view because i have to put each array in table. Maybe something like this:
// 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?
I would be grateful for any help
回答1:
You could use an object with the grouped items. It works for any tags and allows a list of all tags with Object.keys(grouped)
, if required.
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>');
回答2:
If your tag names are known in advance and limited
then simply
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";
});
Or you can create a JSON object keeping the Tag Names like
var tags = {
"Fruit" : [],
"Sport" : [],
"Kitchen" : [],
};
for(var tag in tags)
{
tags[tag] = dataStuff.filter(function(val){
return val.Tag == tag;
});
}
Now tags.Fruit
will give you the Fruit
array.
来源:https://stackoverflow.com/questions/36833978/how-to-split-array-dynamically-based-on-single-value-in-javascript-node-js