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

标签 javascript arrays node.js pug

我需要在 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/

相关文章:

javascript - jQuery/JavaScript : use PHP return value as javaScript array

mysql - 在 Express.js 应用程序中处理 Mysql 数据库的最佳方法是什么?

node.js - Protractor 偶尔无法使用 EADDRINUSE 127.0.0.1 :4444 error 执行测试

apache - 如何在 node-http-proxy 旁边使用虚拟主机?

javascript - Bootstrap 3 popover 在跨两条线上使用时位置错误

javascript - React函数参数是Proxy?

javascript - 使用 Javascript 注入(inject) SVG 的后备

javascript - Jquery append 两个具有不同类的html页面

javascript - 使用 javascript reduce 过滤对象数组,以找到最低的计算统计数据

javascript - 如何将其拆分为 token ?