【问题标题】:append dictionaries to an array using forloop(each) in jquery在 jquery 中使用 for loop(each) 将字典附加到数组
【发布时间】:2013-11-15 06:42:35
【问题描述】:

我有像下面这样从服务器获取的 json 数据

result =     [
      {"transactions": 7, "products__name": "mark"}, 
      {"transactions": 12, "products__name": "vicky"}, 
      {"transactions": 30, "products__name": "daniel"},   
      {"transactions": 6, "products__name": "hurray "}]

现在我想在上面的 json 响应中添加额外的项目并更改字典中的键名,我想要以下格式的结果

 result =    [
        { label: "mark",  data: 7, color: "#4572A7"},
        { label: "vicky",  data: 12, color: "#4572A7"},
        { label: "daniel",  data: 30, color: "#4572A7"},
        { label: "hurray",  data: 6, color: "#4572A7"},
    ];

我想用jquery做上面的逻辑并做了以下

      var array = [];
      var dictionary = {};
      $.each(result, function(key,val){
              dictionary['label'] = val.products__name;
              dictionary['data'] = val.revenue;
              dictionary['color'] = '#4572A7';
              console.log(dictionary);
            array.push(dictionary)
          });
         console.log(array);
});

所以从上面的 jquery 循环代码中,我可以遍历 json 数组并可以创建一个具有不同标签和项目的字典,但是当我将它推入 new array 时,只有起始字典被重复像同一条记录一样插入到数组中会在数组中显示 4 次

那么我的代码有什么问题,谁能告诉我需要做什么才能将不同的 dic 项推送到新数组?

【问题讨论】:

    标签: jquery arrays json for-loop


    【解决方案1】:

    使用$.map()

    var colors = [' #bee485', '#f67d79', '#fdd35b', '#a8eaf7'];
    var dictionary = $.map(result, function (rec, idx) {
        return {
            label: rec.products__name,
            data: rec.transactions,
            color: colors[idx % colors.length]
        }
    })
    

    演示:Fiddle

    【讨论】:

    • 如何将这个创建的字典附加到列表中?,实际上我想以我在问题中提到的格式创建一个字典列表
    • k 可能是我的术语不同,反正我想要这种格式的结果 result = [ { label: "mark", data: 7, color: "#4572A7"}, { label: " vicky”,数据:12,颜色:“#4572A7”},{标签:“丹尼尔”,数据:30,颜色:“#4572A7”},{标签:“欢呼”,数据:6,颜色:“#4572A7 "}, ];
    • 太好了,谢谢,我们也可以像 if index = 0, color= something 这样的方式来做,实际上我想用这个数据来显示一个使用 flot 库的饼图,所以想添加不同的颜色不同的物品对吗?所以我确信我只会得到五个项目,所以如果 index = 0 颜色应该是#bee485,索引 1 项目颜色应该是 #f67d79, 2 = #fdd35b, 3=#a8eaf7 ?
    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 2012-05-14
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2015-08-30
    相关资源
    最近更新 更多