如何根据JavaScript Node.js中的单个值动态拆分数组

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

本文关键字:单个值 动态 拆分 数组 js 何根 JavaScript Node      更新时间:2023-09-26

我需要根据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'}
];

我希望数组按 Tag 拆分,例如。

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

或者,您可以创建一个 JSON 对象,保留标签名称,例如

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

现在tags.Fruit将为您提供Fruit数组。