How to split an array dynamically based on a single value in JavaScript Node.js

I need to split an array dynamically based on a single value in JavaScript.

I have 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 the arrays to be tagged, for example.

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 there are more Tags in the dataStuff array , then as a result there will be more arrays. Anyway, I have no idea how to do this. I am using node.js + Jade (for viewing) and I think the best idea would be to do this when viewing, because I have to put each array in a 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

+4
source share
2 answers

. 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>');
+3

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";
});

JSON, ,

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

tags.Fruit Fruit.

0

All Articles