在javascript中规范化现有数据集的最有效方法

时间:2013-01-22 18:36:58

标签: javascript arrays sorting normalize

我有一个平坦的数据集,我想要规范化。数据集是现有的,源不可更改,因此定义更好的数据结构不是一种选择。我已设法“规范化”并重组数据,但我不确定当行数开始增长时效率如何?这就是我所拥有的,就像我说它只是寻找更优雅的解决方案......

这是理想输出的样子

    {ArticleID: "ABC123", 
Status: "Scheduled", 
Articles: { 
  ArticleID: "ABC123", 
  Region: US, 
  PubTypeID: "EO", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "03/02/2013"
  },{ 
  ArticleID: "ABC234", 
  Region: US, 
  PubTypeID: "EO", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "03/02/2013"
  }
}

Here is a link to jsFiddle

$(document).ready(function(){

var data = new Array( 
{ 
  ArticleID: "ABC123", 
  Region: 'US', 
  PubTypeID: "EO", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "03/02/2013"
},
{ 
  ArticleID: "ABC123", 
  Region: 'RU', 
  PubTypeID: "EO", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "04/02/2013"
},
{ 
  ArticleID: "ABC763", 
  Region: 'EO', 
  PubTypeID: "EO", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "03/02/2013"
},
{ 
  ArticleID: "ABC498", 
  Region: 'JP', 
  PubTypeID: "EN", 
  PubType: "Europe Order", 
  Created: "01/01/2013", 
  Scheduled: "03/02/2013"
}
);

var Articles = new Array(); 
var pID = "";
var cID = "";

$.each(data, function(i, item) {
cID = item.ArticleID;
var entries = new Array();
if(cID != pID)
{
    $.each(data, function(j, item2) {
        var entry = new Object();
        if(cID === item2.ArticleID)
        {
            entry.ArticlID = item2.ArticleID;
            entry.Region = item2.Region;
            entry.PubTypeID = item2.PubTypeID
            entries.push(entry);
        }
    });
    Articles.push({ArtilceID: cID, Entries: entries})
    pID = cID
}
});

alert(Articles.length);
alert(Articles[0].Entries.length);


});

1 个答案:

答案 0 :(得分:0)

一次迭代就足够了。您可以使用利用查找对象的groupBy操作:

var byId = {};
for (var i=0; i<data.length; i++)
    if (data[i].ArticleID in byId)
        byId[data[i].ArticleID].push(data[i]);
    else
        byId[data[i].ArticleID] = [data[i]];

我不知道你究竟需要什么,但是你可以通过这个方式轻松地获得原始代码构建的结构:

var Articles = [];
for (var id in byId)
     Articles.push({
        ArtilceID: id,
        Entries: $.map(byId[id], function(item) {
            return {
                ArticlID: item.ArticleID,
                Region: item.Region,
                PubTypeID: item.PubTypeID
            };
        }) // not sure why you need to clone them, though
     });