为数组分配两个动态键

时间:2014-11-07 12:37:41

标签: javascript coffeescript

我一直试图这样做一个小时,我无法弄清楚。

我有这个:

data =  [
      {
        "_id": {
          "cid": "gbrzjauzju",
          "source": "iwowrzlocc"
        },
        "revenue": 0,
        "leads": 484,
        "count": 25400
      },
      {
        "_id": {
          "cid": "lewyhgnnhz",
          "source": "iwowrzlocc"
        },
        "revenue": 0,
        "leads": 166,
        "count": 9821
      },
    ]

我使用[' cid',' source']传递过滤器作为可变过滤器,因此我可以将其作为过滤器[0]过滤器[1]

进行访问

我想做的是:

arr = {}
for item in data
   arrdata =
      revenue: item.revenue
      leads: item.leads
      clicks: item.count
   arr['results'][item._id.filters[0]][item._id.filters[1]] = arrdata

我想将cid和source的值设置为键名作为键名,所以它就像这样:

results =
   iwowrzlocc =
      lewyhgnnhz =
         revenue: 0
         leads: 166
         clicks: 9821
      gbrzjauzju =
         revenue: 0
         leads: 484
         clicks: 25400

我究竟能做到这一点?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您是否尝试过不使用item._id.filters [0]中的“点语法”?

如果我是你,我会试着分开最后一句话:

var arr = {};
var item_results = {};
var item_cid = {};
for (i in data) {
    var item = data[i];
    var array_data = {
        revenue: item.revenue,
        leads: item.leads,
        count: item.count
    };
    item_cid[item._id[filters[1]]] = array_data;
    item_results[item._id[filters[0]]] = item_cid;
};
arr['results'] = item_results;

只是为了让代码更容易识别可能出现的问题。我希望我能以某种方式帮助你! :)