模块化方法中的 Javascript 对象排序和添加新属性

标签 javascript coding-style

我有以下 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

演示在这里http://jsfiddle.net/1b51eqoq/

关于模块化方法中的 Javascript 对象排序和添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202323/

相关文章:

javascript - 以json形式存储localstorage值

Python PEP 8 文档字符串行长度

javascript - 顶级 reducer 中的 redux 状态选择器

javascript - 在第一个结束后播放第二个 Flash 视频

javascript - 在 JavaScript 中将字符串转换为整数

php - javascript、ajax、PHP 插入 onSubmit 不工作...POST 未设置

c# - 可以返回字符或字符串的 c# 方法的返回值或输出参数?

f# - 有风格地学习 F#

c++ - 介绍 "auto"的同义词

javascript - Facebook 页面点赞计数