我有以下 javascript 对象
mData=[{A: "148.0", Bit: 27 ,Ic: "0.4",ked: "229.0",Ted: "228.9985"},
{A: "148.0", Bit: 27 ,Ic: "0.4",ked: "229.0",Ted: "2285"},
{A: "148.0", Bit: 17 ,Ic: "0.4",ked: "259.0",Ted: "28"},
{A: "148.0", Bit: 27 ,Ic: "0.4",ked: "279.0",Ted: "28"},
{A: "148.0", Bit: 27 ,Ic: "0.4",ked: "239.0",Ted: "82"},
{A: "148.0", Bit: 17 ,Ic: "0.4",ked: "219.0",Ted: "22"},
{A: "148.0", Bit: 16 ,Ic: "0.4",ked: "239.0",Ted: "22"},
{A: "148.0", Bit: 17 ,Ic: "0.4",ked: "259.0",Ted: "22"}];
我试图根据它们的位属性将它们分开。我想出了如下非常简单的算法,但它既不是模块化的也不是通用的。我怎样才能让下面的代码更通用。
color=["red","blue","green"];
data1=[];data2=[];data3=[];
$.each(mData, function (i, wData){
if(wData.Bit===27)
{
wData.color=color[0];
data1.push(wData);
}
else if(wData.Bit===17)
{
wData.color=color[1];
data2.push(wData);
}
else
{
wData.color=color[2];
data3.push(wData);
}
});
除此之外,我想在推送相应数据之前为每个对象添加一个颜色属性,比方说if BIT>27 color='red', if BIT<27&BIT>17 color='blue', if BIT<17 color='yellow'.
这是 fiddle :http://jsfiddle.net/vbLz9zc9/2/
最佳答案
也许像这样使用reduce
var create_map = function(mData, colors, indexes) {
return mData.reduce( function(res, curr) {
var i = indexes[curr.Bit] || 0;
curr.color = colors[i];
( res[i] = res[i] || [] ).push(curr);
return res;
},[]);
}
// define colors and bits which to place into index
var colors = ["red","blue","green"],
indexes = { 17 : 1, 27 : 2}; // zero default, 17 => index 1
var res = create_map( mData, colors, indexes );
// res[0] = array of all
// res[1] = array of Bits == 17
// res[2] = array of Bits == 27
关于模块化方法中的 Javascript 对象排序和添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202323/