分组JavaScript对象和自定义

时间:2015-05-18 00:09:36

标签: javascript

我有以下实现及其功能

https://jsfiddle.net/9mv6w0da/

输入

dataSet[0].data= [
    {color:"yellow",weight:12}
   ,{color:"yellow", weight:12}
   ,{color:"yellow", weight:12}
   ,{color:"red",weight:13}
   ,{color:"red", weight:13}
];          
dataSet[1].data= [
    {color:"yellow",weight:12}
   ,{color:"yellow", weight:12}
   ,{color:"red",weight:13}
   ,{color:"red",weight:13}
   ,{color:"blue",weight:11}
   ,{color:"blue",weight:11}
];

当前输出

an[0]=[
   {color:"yellow",weight:12}
   ,{color:"yellow",weight:12}
   ,{color:"yellow",weight:12}
   ,{color:"yellow",weight:12}
   ,{color:"yellow",weight:12}
]
an[1]=[
    {color:"red",weight:13}
   ,{color:"red",weight:13}
   ,{color:"red",weight:13}
   ,{color:"red",weight:13}
]
an[2]=[{color:"blue",weight:11},{color:"blue",weight:11}]

我想添加{color:null, weight:null}  当我对来自不同javascript对象的数据进行分组时。

伪代码:    dataSet [0](颜色,重量)+ {color:null,weight:null} + dataSet [1](颜色,重量)

如果你看看所需的输出an[0],首先three objects来自dataSet[0],而最后two objects来自dataSet[1]。当我将它们组合在一起时,我想添加{color:null, weight:null}

所需输出

an[0]=[
       {color:"yellow",weight:12}
       ,{color:"yellow",weight:12}
       ,{color:"yellow",weight:12}
       ,{color:null, weight:null}
       ,{color:"yellow",weight:12}
       ,{color:"yellow",weight:12}
    ]
    an[1]=[
        {color:"red",weight:13}
       ,{color:"red",weight:13}
       ,{color:null, weight:null}
       ,{color:"red",weight:13}
       ,{color:"red",weight:13}
    ]
    an[2]=[{color:"blue",weight:11},{color:"blue",weight:11}]

2 个答案:

答案 0 :(得分:1)

您可以添加额外的属性来指示什么是数组编号,之后将该逻辑(添加额外的对象)放入groupby方法。

var i = 0 ; 
var dataSet1 = dataSet.map(function(obj){
obj.map(function(objj){
    objj.arrkey = i ; 
    return objj;
});
i = i+1;
return obj;

});


function groupBy(arr, f) {
 var result = {};
 var arrKey = {} ; 
 arr.forEach(function(elem) {
 var fElem = f(elem),
    list = result[fElem] || [],
    arr = arrKey[fElem] ; 

  if(arr === undefined){
      arr = elem.arrkey;}

if(elem.arrkey != arr)  
{ 
    list.push(nullobj);
}
list.push(elem);
arrKey[fElem] = elem.arrkey;
result[fElem] = list;
});
return result;
}

https://jsfiddle.net/5swdjg3f/

中的示例

答案 1 :(得分:0)

combined = data1.concat ([{color: null, weight: null}]).concat (data2)

但不要这样做。使用一个数组数组,其中每个源都有自己的子数组,或者更好的是,用一个方法编写一个类,清楚地说明为什么这些集被分开,因为这个代码的下一个人不知道{{{ 1}} y元素表示。他也不能通过一些其他标准对事物进行分组,而不会消化你的分隔符并添加他自己的分隔符,这同样是hack-y。