从Node.JS中的平面集中提取分层数据集 [英] Extract a hierarchical dataset from a flat set in Node.JS

查看:46
本文介绍了从Node.JS中的平面集中提取分层数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript/Node.JS将平面数据集中的所有项目组合在一起以形成分层数据集.

I am trying to get all the items in a flat dataset that are grouped together to form a hierarchical dataset using Javascript/Node.JS.

我有一个解决方案,但我认为这不是最优雅的,它可能会得到改善.

I have a solution, but I don't think it's the most elegant and it could probably be improved.

我在此处基于答案的解决方案找到所有具有匹配ID的对象javascript

I based my solution of the answer here Find all objects with matching Ids javascript

我的数据集如下:

let data = [{cid: 1, clbl: 'Rush Shipping', pid:5, plbl: 'FedEx'},
        {cid: 2, clbl: 'Standard Shipping', pid:5, plbl: 'FedEx'},
        {cid: 3, clbl: 'First Class', pid:8, plbl: 'USPS'},
        {cid: 4, clbl: 'Std', pid:9, plbl: 'DHL'},
        {cid: 5, clbl: 'Canada Post', pid:1, plbl: 'Canada Post'},
       ];

我希望我的输出是这样的:

I would like my output to be something like this:

[ { pid: 5,
    plbl: 'FedEx',
    methods: [
       {
         cid: 1,
         clbl: 'Rush Shipping',
       },
       {
         cid: 2,
         clbl: 'Standard Shipping',
       },
   },
   { pid: 8,
    plbl: 'USPS',
    methods: [
       {
         cid: 3,
         clbl: 'First Class',
       },
   },
   { pid: 9,
    plbl: 'DHL',
    methods: [
       {
         cid: 4,
         clbl: 'Std',
       },
   },
   { pid: 1,
    plbl: 'Canada Post',
    methods: [
       {
         cid: 5,
         clbl: 'Canada Post',
       },
   },
 ]

我整理了一些可行的代码,但我想有一种更优化的方法可以做到这一点,并认为我会将其放到SO社区中.

I threw together some code that works, but I imagine there has be be a more optimized way to do this and thought I would put it to the SO community.

这是我的解决方案:

var roots = [];

var all = {};
data.forEach(function(item) {
    all[item.pid] = item;
})
Object.keys(all).forEach(function(pid) {
  var items = data.filter(x => x.pid == pid);
  var addItem = {};
    items.forEach(function(item, j) {
    if (j === 0){
        addItem = {pid:item.pid, label:item.plbl, methods:[]};
     }
    addItem.methods.push({cid: item.cid, label: item.clbl});
    });
  roots.push(addItem);
})
console.log(roots);

推荐答案

从内存/速度的角度来看,我不认为这是优化"的,但它要短一些.

I don't think this is more 'optimized' from a memory/speed standpoint but it is a little shorter.

let new_data = Object.values(data.reduce(function(o, d) {
    o[d.pid] = o[d.pid] || {pid: d.pid, plbl: d.plbl, methods:[]};
    o[d.pid].methods.push({cid: d.cid, clbl: d.clbl});
    return o;
}, {}));

基本上利用 reduce 方法,以构建一个组合的 all 对象.然后使用 Object.values()从存储在 all 对象中的值创建一个数组,而不是手动推送它们.

Basically take advantage of the reduce method in order to build one combined all object. Then use Object.values() to create an array from the values stored in the all object instead of manually pushing them.

这篇关于从Node.JS中的平面集中提取分层数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆