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

ぐ巨炮叔叔 提交于 2020-01-03 15:34:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!